<?php
namespace app\common\service\order;
use app\common\model\member\MemberBillModel;
use app\common\model\Merchant\MerchantBillModel;
use app\common\model\order\ShopOrderCommentModel;
use app\common\model\order\ShopOrderLogModel;
use app\common\model\order\ShopOrderModel;
use app\common\cache\order\ShopOrderCache;
use app\common\model\product\ShopProductEnterModel;
use app\common\model\product\ShopProductModel;
use app\common\model\product\ShopProductTypeModel;
use app\common\model\setting\SettingPriceConditionModel;
use app\common\model\setting\SettingPriceRangeModel;
use app\common\model\setting\SettingRefundModel;
use app\common\model\setting\SettingStorePlatformModel;
use app\common\service\file\FileService;
use app\common\service\file\MerchantFileService;
use app\common\service\file\SettingService;
use app\common\service\member\MemberAccountService;
use app\common\service\member\MemberMessageService;
use app\common\service\member\MemberService;
use app\common\service\merchant\MerchantService;
use app\common\service\product\ShopProductService;
use app\common\service\promotion\PromotionUserService;
use app\common\service\setting\RegionService;
use app\common\service\system\SettingService as SystemSettingService;
use app\common\service\member\SettingService as MemberSettingService;
use app\common\service\webscoket\CacheRedisService;
use app\merchant\controller\order\ShopOrder;
use DateTime;
use think\facade\Db;

/**
 * 订单管理
 */
class ShopOrderService
{
    /**
     * 添加、修改字段
     * @var array
     */
    public static $edit_field = [
        'id/d' => '',//主键
        'merchant_id/d' => null,//商家ID
        'merchant_shop_id/d' => null,//店铺ID
        'store_platform_id/d' => null,//店铺平台ID
        'setting_refund_id/d' => null,//返款类型【平台补贴、商家返款】
        'shop_product_type_id/d' => null,//活动类型【平台补贴、垫付任务、浏览任务】
        'shop_product_type_code' => '',//活动类型编码
        'shop_product_id/d' => null,//商品表ID
        'shop_product_enter_id/d' => null,//进店方式ID
        'shop_product_price_ids' => '',//费用明细ID(多个逗号隔开)
        'member_id' => '',//接单人id
        'order_on' => '',//订单号
        'status' => '',//订单状态：-1、撤销  0、待上架  1、待自选 2、待接单  3、待操作 4、待发货  5、待评价 6、评价待审核 7完成 8、审核未通过 9、暂停
        'principal' => '',//订单本金
        'commission' => '',//订单佣金
        'actual_amount' => '',//实付金额
        'add_comment_commission' => '',//追评佣金
        'revoke_type' => '',//撤销类型：0、商家撤销 1、买家撤销
        'revoke_remark' => '',//撤销备注
        'auth_remark' => '',//审核备注
        'answer' => '',//宝贝详情回答
        'screenshot_image_id' => '',//订单截图ID
        'is_delete' => '',//是否删除，1是0否
        'create_uid' => '',//添加用户id
        'update_uid' => '',//修改用户id
        'delete_uid' => '',//删除用户id
        'revoke_uid' => '',//撤销用户id
        'create_time' => '',//创建时间
        'update_time' => '',//修改时间
        'delete_time' => '',//删除时间
        'meet_time' => '',//接单时间
        'revoke_time' => '',//撤销时间
        'principal_time' => '',//本金返款时间
        'commission_time' => '',//佣金发放时间
    ];
    /**
     * 订单管理列表
     *
     * @param array  $where 条件
     * @param int    $page  页数
     * @param int    $limit 数量
     * @param array  $order 排序
     * @param string $field 字段
     * @param int $nums_type 订单数量统计类型：1、按状态统计  2、自行买号匹配订单按平台统计  3、浏览任务统计 4、商家返款统计 5、买家端订单列表
     *
     * @return array
     */
    public static function list($where = [], $page = 1, $limit = 10,  $order = [], $field = '',$nums_type=1)
    {
        $sql = self::getListSql($where,$order,$field);
        if ($page == 0 || $limit == 0) {
            return json_decode(json_encode(Db::query($sql)), true);
        }
        $count =  Db::query("select count(*) as count from (".$sql.") as co");
        $count=$count[0]['count'];
        $pages = ceil($count / $limit);
        // 计算偏移量
        $offset = ($page - 1) * $limit;
        $list = Db::query($sql. " LIMIT $offset, $limit");
        // 获取当前日期的前3天和前1天的日期
        $three_days_ago = date('Y-m-d H:i:s', strtotime('-3 days'));
        $one_day_ago = date('Y-m-d H:i:s', strtotime('-1 day'));
        $merchantId = mer_id();
        //获取接单操作分钟
        if($nums_type==5){
            $setting = SystemSettingService::info('order_operating_time');
        }
        //查询图片路径
        foreach ($list as $key=>$item) {
            //店铺平台图片
            if(isset($item['platform_image_id'])){
                $file = FileService::info($item['platform_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['platform_image_url'] =$file['file_url'];
                }
            }
            //商品缩略图
            if(isset($item['goods_image_id'])){
                $file = MerchantFileService::info($item['goods_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['goods_image_url'] =$file['file_url'];
                }
                if($nums_type==5){
                    // 查找最后一个点的位置
                    $lastDotPosition = strrpos($file['file_path'], '.');
                    $newFilePath = substr($file['file_path'], 0, $lastDotPosition) . '_pixelated' . substr($file['file_path'], $lastDotPosition);
                    $new_file_path = self::pixelateImage($file['file_path'],$newFilePath,30);
                    if($new_file_path){
                        $list[$key]['goods_image_url'] = file_url($new_file_path);
                    }
                }
            }
            //做单图
            if(isset($item['screenshot_image_id'])){
                $file = FileService::info($item['screenshot_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['screenshot_image_url'] =$file['file_url'];
                }
            }
            //物流截图
            if(isset($item['logistics_image_id'])){
                $file = FileService::info($item['logistics_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['logistics_image_url'] =$file['file_url'];
                }
            }
            //物流截图
            if(isset($item['evaluate_image_id'])){
                $file = FileService::info($item['evaluate_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['evaluate_image_url'] =$file['file_url'];
                }
            }
            //收货地址
            $item['ac_region_str'] = "";
            if(isset($item['ac_region_id'])){
                $region = RegionService::info($item['ac_region_id']);
                if(isset($region['region_fullname'])){
                    $list[$key]['ac_region_str']  =$region['region_fullname'];
                }
            }
            //状态名称
            $list[$key]['status_title'] = ShopOrderModel::getStatus($item['status'],2);

            //评论类型
            if(isset($item['comment_type'])){
                $list[$key]['comment_type_str'] = SettingPriceRangeModel::getCommentType($item['comment_type'],1);
            }
            //进店方式
            if(isset($item['enter_type'])){
                $list[$key]['enter_type_str'] = SettingPriceRangeModel::getEnterType($item['enter_type'],1);
            }
            //二维码
            $list[$key]['enter_qr_image_url'] ="";
            if(isset($item['enter_qr_image_id']) && $item['enter_qr_image_id']){
                $file = MerchantFileService::info($item['enter_qr_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['enter_qr_image_url'] =$file['file_url'];
                }
            }
            //是否显示催评
            $list[$key]['is_urge'] = false;
            if($item['status'] == ShopOrderModel::getStatus('o_evaluate',1) && $item['ship_time']<=$three_days_ago){
                $urge = Db::name('shop_order_urge')
                    ->where('shop_order_id',$item['id'])
                    ->where('is_delete', 0)
                    ->order('create_time','desc')
                    ->field('id,create_time')
                    ->find();
                if(!$urge || $urge['create_time']<=$one_day_ago){
                    $list[$key]['is_urge'] = true;
                }
            }
            //查询发布评论/追加评论
            $list[$key]['order_comment2'] = null;
            $list[$key]['order_comment3'] = null;
            $list[$key]['order_comment_status2'] = 0;
            $list[$key]['order_comment_status3'] = 0;
            $order_comments = Db::name('shop_order_comment')->where('is_delete',0)->where('shop_order_id',$item['id'])->select()->toArray();
            foreach ($order_comments as $k=>$v){
                //好评视频
                if($v['comment_vido_id']){
                    $file = MerchantFileService::info($v['comment_vido_id']);
                    if($file && isset($file['file_url'])){
                        $v['comment_vido_url'] =$file['file_url'];
                    }
                }
                //好评图片
                if($v['comment_image_id']){
                    $files = Db::name('merchant_file')
                        ->where('is_disable',0)
                        ->where('is_delete',0)
                        ->where('file_id','in',explode(',',$v['comment_image_id']))
                        ->when($merchantId>0, function($query) use ($merchantId) {
                            $query->where('mer_id', $merchantId);
                        })
                        ->select()
                        ->toArray();
                    foreach ($files as $fk=>$fv){
                        $files[$fk]['file_url'] = SettingService::fileUrl($fv);
                    }
                    $v['comment_image_id'] =$files;
                }else{
                    $v['comment_image_id'] =[];
                }
                if($v['evaluate_image_id']){
                    $file = FileService::info($v['evaluate_image_id']);
                    if($file && isset($file['file_url'])){
                        $v['evaluate_image_url'] =$file['file_url'];
                    }
                }

                $list[$key]['order_comment'.$v['comment_status']] = $v;
                $list[$key]['order_comment_status'.$v['comment_status']] =$v['status'];
            }

            //收款二维码
            if(isset($item['member_wechat_image_id']) && $item['member_wechat_image_id']){
                $file = FileService::info($item['member_wechat_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['member_wechat_image_url'] =$file['file_url'];
                }
            }
            if(isset($item['member_alipay_image_id']) && $item['member_alipay_image_id']){
                $file = FileService::info($item['member_alipay_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['member_alipay_image_url'] =$file['file_url'];
                }
            }
            //申诉与查看申诉按钮控制
            $list[$key]['is_appeal'] = false;
            $list[$key]['is_show_appeal'] = false;
            $last_appeal = Db::name('shop_order_appeal')->where('shop_order_id',$item['id'])->order(['status' => 'asc', 'create_time' => 'desc'])->field('id,status')->find();
            if($last_appeal){
                $list[$key]['is_show_appeal'] = true;
                if($last_appeal['status']>=2){
                    $list[$key]['is_appeal'] = true;
                }
            }else{
                $list[$key]['is_appeal'] = true;
            }
            //利润计算
            $list[$key]['profit'] =self::profitHandle($item);
            //虚拟差价，只参与页面显示，未实际进行多退少补
            if(array_key_exists('principal', $item) && array_key_exists('actual_amount', $item)){
                $list[$key]['difference_amount_show'] =bcsub($item['principal'],$item['actual_amount'],2);
            }
            //店铺名称处理
            if (isset($item['shop_title']) && $nums_type==5 && array_key_exists('status', $item) && $item['status']== ShopOrderModel::getStatus('o_operation',1)){
                $list[$key]['shop_title'] = self::hideSpace($item['shop_title'],2);
            }
            //操作订单倒计时
            if ($nums_type==5 && $setting['order_operating_time']>0 && isset($item['meet_time']) && array_key_exists('status', $item) && $item['status']== ShopOrderModel::getStatus('o_operation',1)){
                $current_time = strtotime('-'.$setting['order_operating_time'].' minutes');
                $list[$key]['time_diff_in_seconds'] =strtotime($item['meet_time'])-$current_time;
            }
            //平台补贴商品本金与佣金处理
            if($nums_type==5 && isset($item['shop_product_type_code']) && $item['shop_product_type_code']=='PTBT' && isset($item['order_price'])){
                $list[$key]['commission'] =bcadd($item['commission'], $item['principal'],2);
                $list[$key]['principal'] =$item['order_price'];
            }
        }
        //统计查询
        switch ($nums_type){
            case 2:
                $status_nums =[];
                break;
            case 3:
                $status_nums = self::getStatusNum($nums_type);
                break;
            case 4:
                $status_nums = self::getMerRefundStatusNum();
                break;
            case 5:
                $status_nums = [];
                break;
            default:
                $status_nums = self::getStatusNum($nums_type);
                break;
        }
        return compact('count', 'pages', 'page', 'limit', 'list','status_nums');
    }

    /**
     * 订单利润计算
     * @Author: 易军辉
     * @DateTime:2024-09-25 15:52
     * @param $order 订单信息
     * @return string
     */
    private static function profitHandle($order)
    {
        $profit = 0;
        if(
            array_key_exists('id', $order)
            && array_key_exists('mer_commission', $order)
            && array_key_exists('is_mer_commission', $order)
            && array_key_exists('commission', $order)
            && array_key_exists('is_commission', $order)
            && array_key_exists('status', $order)
        ){
            //推广费
            $profit = Db::name('shop_order_promotion')
                ->where('shop_order_id',$order['id'])
                ->where('is_delete',0)
                ->sum(Db::raw('(`one_amount` + `two_amount` + `three_amount` + `one_promotion_amount` + `two_promotion_amount` + `three_promotion_amount`)'));
            if(!$profit){
                $profit = 0;
            }
            //商家支付佣金
            $mer_commission = $order['mer_commission'];
            if($order['is_mer_commission']==2){//佣金已退
                $mer_commission = 0;
            }
            //买家佣金
            $commission = $order['commission'];
            if($order['is_commission']==2){//佣金已退
                $commission = 0;
                $profit = 0;
            }
            //订单已撤销
            if($order['status']==ShopOrderModel::getStatus('o_revoke',1)){
                if($order['is_commission']!=1){
                    $commission = 0;
                }
            }
            $profit =bcsub($mer_commission, bcadd($commission, $profit,2),2);
        }
        return $profit;
    }
    /**
     * 图片加网格线
     * @Author: 易军辉
     * @DateTime:2024-09-02 16:00
     * @param $src
     * @param $dst
     * @param $lineThickness
     * @return mixed
     */
    private static function pixelateImage($src, $dst, $lineThickness = 5)
    {
        //检查原文件是否存在
        if(!file_exists($src)){
            return $src;
        }
        // 检查目标文件是否已存在
        if (file_exists($dst)) {
            // 如果文件已存在，直接返回路径
            return $dst;
        }
        // 检查 GD 扩展是否已启用
        if (!extension_loaded('gd')) {
            exception('GD 扩展未启用');
        }

        // 获取图片信息
        list($width, $height, $type) = getimagesize($src);

        // 根据图片类型创建图像资源
        switch ($type) {
            case IMAGETYPE_JPEG:
                $img = imagecreatefromjpeg($src);
                break;
            case IMAGETYPE_PNG:
                $img = imagecreatefrompng($src);
                break;
            case IMAGETYPE_GIF:
                $img = imagecreatefromgif($src);
                break;
            default:
                return $src;
                exception('不支持的图片类型');
        }

        // 设置线条颜色（黑色），可以根据需要调整颜色
        $lineColor = imagecolorallocatealpha($img, 0, 0, 0,50);

        // 设置线条粗细
        imagesetthickness($img, $lineThickness);

        // 绘制水平和垂直线条形成9格网格
        // 水平线
        imageline($img, 0, $height / 3, $width, $height / 3, $lineColor);
        imageline($img, 0, 2 * $height / 3, $width, 2 * $height / 3, $lineColor);

        // 垂直线
        imageline($img, $width / 3, 0, $width / 3, $height, $lineColor);
        imageline($img, 2 * $width / 3, 0, 2 * $width / 3, $height, $lineColor);

        // 绘制边框线
        imagerectangle($img, 0, 0, $width - 1, $height - 1, $lineColor);

        // 保存处理后的图片
        switch ($type) {
            case IMAGETYPE_JPEG:
                imagejpeg($img, $dst);
                break;
            case IMAGETYPE_PNG:
                imagepng($img, $dst);
                break;
            case IMAGETYPE_GIF:
                imagegif($img, $dst);
                break;
        }

        // 销毁图像资源
        imagedestroy($img);

        return $dst;
    }
    /**
     * 组装查询SQL
     * @Author: 易军辉
     * @DateTime:2024-06-12 19:56
     * @param $where
     * @param $order
     * @return string
     */
    private static function getListSql($where = [], $order = [],$field = '')
    {
        /***************************查询字段***********************************************/
        if (empty($field)) {
            $field = 'platform.title as platform_title,
            platform.image_id as platform_image_id,
            type.title as type_title,
            shop.title as shop_title,
            refund.title as refund_title,
            goods.id as goods_id,
            goods.third_id as goods_third_id,
            goods.goods_title,
            goods.image_id as goods_image_id,
            goods.goods_spec,
            goods.goods_type,
            product.h_pay_time,
            product.id as product_id,
            enter.comment_type,
            enter.enter_type,
            enter.keyword as enter_keyword,
            enter.qr_image_id as enter_qr_image_id,
            account.consignee as ac_consignee,
            account.phone as ac_phone,
            account.region_id as ac_region_id,
            account.address as ac_address,
            account.accname,
            a.*';
        }
        /***************************组装条件***********************************************/
        $where_sql = "";
        foreach ($where as $key=>$val){
            $prefix = "a.";
            if(strpos($val[0], '.') !== false){
                $prefix = "";
            }else{
                $prefix = "a.";
            }
            if($where_sql!=""){
                $where_sql .=" and ";
            }
            if($val[0] == 'platform_ids' && isset($val[2])){
                $where_sql .="platform.id in(".implode(',',SettingStorePlatformModel::handleTaobaoIds($val[2])).")";
            }else if($val[0] == 'product_type_ids' && isset($val[2])) {
                $where_sql .= "type.id in(" . implode(',', $val[2]) . ")";
            }else if($val[0] == 'pending_time' && ($val[1]=="<" || $val[1]=="<=")) {//接单时间处理
                $where_sql .="(".$prefix.$val[0]." ".$val[1]." '".$val[2]."' or ".$prefix.$val[0]." is null) ";
            }else if(is_array($val[2])) {
                $where_sql .= $prefix . $val[0] . " " . $val[1] . "(" . implode(',', $val[2]) . ")";
            }else if($val[0] == 'status' && $val[2]>=0) {
                $where_sql .= $prefix . $val[0] . " " . $val[1] . " '" . $val[2] . "' ";
            }else if($val[1] == 'is'){
                $where_sql .=$prefix.$val[0]." ".$val[1]." ".$val[2];
            }else{
                $where_sql .=$prefix.$val[0]." ".$val[1]." '".$val[2]."' ";
            }
        }

        /***************************组装排序***********************************************/
        $order_sql = "";
        foreach ($order as $key=>$val){
            if($order_sql!=""){
                $order_sql .=" , ";
            }
            $order_sql .="a.".$key." ".$val." ";
        }
        if($order_sql == ""){
            $order_sql = "a.status asc,a.id desc";
        }
        /***************************组装关联其它表***********************************************/
        $left_join = "";
        if (strpos($field, 'member.') !== false) {
            $left_join .=" LEFT JOIN ya_member as member ON a.member_id = member.member_id ";
        }
        $sql = <<<SQL
            SELECT 
                 {$field}
                FROM ya_shop_order AS a
                -- 关联商品表，取第一条商品
                LEFT JOIN (
                    SELECT goods.*,goods_type.title as goods_type 
                    FROM ya_shop_product_goods as goods
                    -- 关联商品分类
                    LEFT JOIN ya_setting_store_type AS goods_type ON goods.setting_store_type_id = goods_type.id
                    WHERE (goods.shop_product_id,goods.id) IN (
                        SELECT shop_product_id, MIN(id) 
                        FROM ya_shop_product_goods 
                        GROUP BY shop_product_id
                    )
                ) AS goods ON a.shop_product_id = goods.shop_product_id
                -- 关联店铺平台
                LEFT JOIN ya_setting_store_platform AS platform ON a.store_platform_id = platform.id
                -- 关联活动分类	
                LEFT JOIN ya_shop_product_type AS type ON a.shop_product_type_id = type.id
                -- 关联店铺
                LEFT JOIN ya_merchant_shop as shop ON a.merchant_shop_id = shop.id
                -- 关联返款类型
                LEFT JOIN ya_setting_refund as refund ON a.setting_refund_id = refund.id
                 -- 关联商品表
                LEFT JOIN ya_shop_product as product ON a.shop_product_id = product.id
                 -- 关联进店方式
                LEFT JOIN ya_shop_product_enter as enter ON a.shop_product_enter_id = enter.id
                 -- 关联接单账号
                LEFT JOIN ya_member_account as account ON a.member_account_id = account.id
                -- 其它关联表
                {$left_join}
            WHERE
                {$where_sql}
            ORDER BY 
                {$order_sql}
        SQL;
        return $sql;
    }

    /**
     * 查询状态数量
     * @Author: 易军辉
     * @DateTime:2024-07-05 21:04
     * @param $type 类型：1、订单列表 3、浏览任务
     * @return array
     * @throws \think\db\exception\DbException
     */
    public static function getStatusNum($type=1){
        $merchantId = mer_id();
        $where = " where is_delete=0";
        if($merchantId>0){
            $where .=" and merchant_id=".$merchantId;
        }
        //只查询浏览任务的数量
        if($type == 3){
            $where .=" and shop_product_type_code='".ShopProductTypeModel::LLRW."'";
        }
        //根据状态查询数量
        $status_num = Db::query("SELECT status,count(id) as num from ya_shop_order ".$where." GROUP BY status");
        $status_nums = array();

        $status_nums['all'] = Db::name('shop_order')
            ->where('is_delete',0)
            ->when($type == 3,function ($query){
                $query->where('shop_product_type_code',ShopProductTypeModel::LLRW);
            })
            ->when($merchantId>0, function($query) use ($merchantId) {
                $query->where('merchant_id', $merchantId);
            })->count();
        foreach (ShopOrderModel::STATUS as $k => $v) {
            $status_nums[$v['code']] =0;
            foreach ($status_num as $k1 => $v1) {
                if($v1['status'] == $v['value']) {
                    $status_nums[$v['code']] = $v1['num'];
                    break;
                }
            }
        }
        return $status_nums;
    }

    /**
     * 总后端数据统计
     * @Author: 易军辉
     * @DateTime:2024-11-15 11:21
     * @param $where
     */
    public static function adminDashboardStatistics($where=[])
    {
        /***************************组装条件***********************************************/
        $where_sql = "";//平台佣金条件
        $where_sql1 = "";//成交订单条件
        $where_sql2 = "";//退款订单条件
        $bill_where = [];
        $sta_date = date('Y-m-d 00:00:00', strtotime('-29 days'));
        $end_date = date('Y-m-d 23:59:59');
        foreach ($where as $key=>$val){
            $where_sql .=" and ";
            $where_sql1 .=" and ";
            $where_sql2 .=" and ";
            if($val[0] == 'platform_ids' && isset($val[2])) {
                $where_sql .= "store_platform_id in(" . implode(',', SettingStorePlatformModel::handleTaobaoIds($val[2])) . ")";
                $where_sql1 .= "store_platform_id in(" . implode(',', SettingStorePlatformModel::handleTaobaoIds($val[2])) . ")";
                $where_sql2 .= "store_platform_id in(" . implode(',', SettingStorePlatformModel::handleTaobaoIds($val[2])) . ")";
            }else if($val[0] == 'create_time'){//筛选时间
                if($val[1] == '>='){
                    $sta_date=$val[2];
                }else if($val[1] == '<='){
                    $end_date=$val[2];
                }
                array_push($bill_where,$val);
                $where_sql .=" create_time ".$val[1]." '".$val[2]."' ";
                $where_sql1 .=" ship_time ".$val[1]." '".$val[2]."' ";
                $where_sql2 .=" revoke_time ".$val[1]." '".$val[2]."' ";
            }else if(is_array($val[2])) {
                $where_sql .= $val[0] . " " . $val[1] . "(" . implode(',', $val[2]) . ")";
            }else if($val[1] == 'is'){
                $where_sql .=$val[0]." ".$val[1]." ".$val[2];
            }else{
                $where_sql .=$val[0]." ".$val[1]." '".$val[2]."' ";
            }
        }
        $order_where = " is_delete = 0 ";
        $mer_id = mer_id();
        if($mer_id>0){
            $order_where .=" AND merchant_id = ".$mer_id;
            $bill_where[] = ['mer_id','=',$mer_id];
        }
        $status_5 = ShopOrderModel::getStatus('o_evaluate',1);
        $status_6 = ShopOrderModel::getStatus('o_auth',1);
        $status_7 = ShopOrderModel::getStatus('o_success',1);
        $status_10 = ShopOrderModel::getStatus('o_revoke',1);
        $sql = <<<SQL
                SELECT 
                    -- 成交金额
                SUM(CASE WHEN `status` IN ({$status_5}, {$status_6}, {$status_7}) {$where_sql1} THEN actual_amount  ELSE 0 END) AS success_amount,
                    -- 成交订单量
                SUM(CASE WHEN `status` IN ({$status_5}, {$status_6}, {$status_7}) {$where_sql1} THEN 1 ELSE 0 END) AS o_success,
                    -- 退款金额
                SUM(CASE WHEN `status` = {$status_10} {$where_sql2} THEN principal+ difference_amount + mer_commission + add_comment_commission ELSE 0 END) AS revoke_amount,
                    -- 退款订单量
                SUM(CASE WHEN `status` = {$status_10} {$where_sql2} THEN 1 ELSE 0 END) AS o_revoke,
                    -- 平台佣金
                SUM(CASE WHEN `status` IN ({$status_5}, {$status_6}, {$status_7}) {$where_sql1} THEN mer_commission + add_comment_commission ELSE 0 END) AS commission_amount
            FROM 
                ya_shop_order
            where 
                 {$order_where}
            SQL;
        $statistics = Db::query($sql);
        $statistics = $statistics[0];
        //查询充值金额
        $statistics['recharge_amount'] = Db::name('merchant_bill')
            ->where('is_delete',0)
            ->where('type',MerchantBillModel::getType('RECHARGE',1))
            ->where('principal','>',0)
            ->where($bill_where)
            ->sum('principal');
        $statistics['recharge_amount'] = number_format($statistics['recharge_amount'], 2, '.', '');
        return $statistics;
    }

    /**
     * 查询总后端订单统计图
     * @Author: 易军辉
     * @DateTime:2024-11-15 15:43
     * @param $type
     * @return mixed
     */
    public static function adminDashboardOrder($type)
    {
        $legend = [];
        $xAxis = [];
        $series = [];
        switch ($type){
            case '30day':
                $sta_date = date('Y-m-d 00:00:00', strtotime('-29 days'));
                $end_date = date('Y-m-d 23:59:59');
                $s_time = strtotime($sta_date);
                $e_time = strtotime($end_date);
                $dates = [];
                while ($s_time <= $e_time) {
                    $dates[] = date('Y-m-d', $s_time);
                    $s_time = strtotime('next day', $s_time);
                }
                $chart_where = "is_delete =0 and create_time BETWEEN '".$sta_date."' and '".$end_date."'";
                $chart_sql = <<<SQL
                                SELECT 
                                    date_format(create_time,'%Y-%m-%d') as date,
                                        -- 订单数量
                                    count(id) AS order_num,
                                        -- 支付金额
                                    SUM(principal+ difference_amount + mer_commission + add_comment_commission) AS order_amount
                                FROM 
                                    ya_shop_order
                                where 
                                      {$chart_where}
                                GROUP BY date_format(create_time,'%Y-%m-%d')
                            SQL;
                $chart_list = Db::query($chart_sql);
                $order_nums = [];
                $order_amounts = [];
                foreach ($dates as $k => $v) {
                    $order_nums[$k] = 0;
                    $order_amounts[$k] = 0;
                    foreach ($chart_list as $key=>$val){
                        if($val['date'] == $v){
                            $order_nums[$k] = $val['order_num'];
                            $order_amounts[$k] = $val['order_amount'];
                            break;
                        }
                    }
                }
                $series = [
                    ['name'=> '订单金额',
                        'type'=> 'bar',
                        'yAxisIndex'=> 0, // 使用第一个 y 轴（金额）
                        'data'=> $order_amounts,
                        'itemStyle'=> [
                            'color'=> '#50D899'
                        ]
                    ],
                    [
                        'name'=> '订单数',
                        'type'=> 'line',
                        'yAxisIndex'=> 1, // 使用第二个 y 轴（订单数）
                        'data'=> $order_nums, // 上周订单数是本周的 90%
                        'smooth'=> true,
                        'lineStyle'=> [
                            'color'=> '#8FD0F8'
                        ]
                    ]
                ];
                $legend = array_column($series, 'name');
                $xAxis = $dates;
                break;
            case 'week':
                // 获取本周的起始和结束日期（周一到周日）
                $start_of_week = new DateTime('monday this week 00:00:00'); // 本周开始日期（周一）
                $end_of_week = new DateTime('sunday this week 23:59:59'); // 本周结束日期（周日）

                // 获取上周的起始和结束日期（周一到周日）
                $start_of_last_week = new DateTime('monday last week 00:00:00'); // 上周开始日期（周一）
                $end_of_last_week = new DateTime('sunday last week 23:59:59'); // 上周结束日期（周日）

                // 将 DateTime 对象转换为时间戳
                $start_of_week_timestamp = $start_of_week->getTimestamp();
                $end_of_week_timestamp = $end_of_week->getTimestamp();
                $start_of_last_week_timestamp = $start_of_last_week->getTimestamp();
                $end_of_last_week_timestamp = $end_of_last_week->getTimestamp();

                // 获取本周和上周日期列表
                $this_week_dates = [];
                for ($i = $start_of_week_timestamp; $i <= $end_of_week_timestamp; $i = strtotime("+1 day", $i)) {
                    $this_week_dates[] = date('Y-m-d', $i);
                }

                $last_week_dates = [];
                for ($i = $start_of_last_week_timestamp; $i <= $end_of_last_week_timestamp; $i = strtotime("+1 day", $i)) {
                    $last_week_dates[] = date('Y-m-d', $i);
                }
                $chart_where = "is_delete =0 and create_time BETWEEN '".$start_of_last_week->format('Y-m-d H:i:s')."' and '".$end_of_week->format('Y-m-d H:i:s')."'";
                $chart_sql = <<<SQL
                            SELECT 
                                date_format(create_time,'%Y-%m-%d') as date,
                                -- 订单数量
                                count(id) AS order_num,
                                -- 支付金额
                                SUM(principal+ difference_amount + mer_commission + add_comment_commission) AS order_amount
                            FROM 
                                ya_shop_order
                            where 
                                  {$chart_where}
                            GROUP BY date_format(create_time,'%Y-%m-%d')
                            SQL;
                $chart_list = Db::query($chart_sql);
                $of_week_nums=[];
                $of_week_amounts=[];
                $last_week_nums=[];
                $last_week_amounts=[];
                foreach ($last_week_dates as $k => $v) {
                    $last_week_nums[$k] = 0;
                    $last_week_amounts[$k] = 0;
                    foreach ($chart_list as $key=>$val){
                        if($val['date'] == $v){
                            $last_week_nums[$k] = $val['order_num'];
                            $last_week_amounts[$k] = $val['order_amount'];
                            break;
                        }
                    }
                }
                foreach ($this_week_dates as $k => $v) {
                    $of_week_nums[$k] = 0;
                    $of_week_amounts[$k] = 0;
                    foreach ($chart_list as $key=>$val){
                        if($val['date'] == $v){
                            $of_week_nums[$k] = $val['order_num'];
                            $of_week_amounts[$k] = $val['order_amount'];
                            break;
                        }
                    }
                }
                $series = [
                    ['name'=> '本周金额',
                        'type'=> 'bar',
                        'yAxisIndex'=> 0, // 使用第一个 y 轴（金额）
                        'data'=> $of_week_amounts,
                        'itemStyle'=> [
                            'color'=> '#50D899'
                        ]
                    ],
                    ['name'=> '上周金额',
                        'type'=> 'bar',
                        'yAxisIndex'=> 0, // 使用第一个 y 轴（金额）
                        'data'=> $last_week_amounts,
                        'itemStyle'=> [
                            'color'=> '#3EB2F6'
                        ]
                    ],
                    [
                        'name'=> '本周订单数',
                        'type'=> 'line',
                        'yAxisIndex'=> 1, // 使用第二个 y 轴（订单数）
                        'data'=> $of_week_nums, // 上周订单数是本周的 90%
                        'smooth'=> true,
                        'lineStyle'=> [
                            'color'=> '#7CDFB2'
                        ]
                    ],
                    [
                        'name'=> '上周订单数',
                        'type'=> 'line',
                        'yAxisIndex'=> 1, // 使用第二个 y 轴（订单数）
                        'data'=> $last_week_nums, // 上周订单数是本周的 90%
                        'smooth'=> true,
                        'lineStyle'=> [
                            'color'=> '#8FD0F8'
                        ]
                    ]
                ];
                $legend = array_column($series, 'name');
                $xAxis = ['周一','周二','周三','周四','周五','周六','周日',];
                break;
            case 'month':
                // 获取本月和上月日期
                $start_of_month = date('Y-m-01');
                $end_of_month = date('Y-m-t');

                $start_of_last_month = date('Y-m-01', strtotime("-1 month"));
                $end_of_last_month = date('Y-m-t', strtotime("-1 month"));

                $this_month_dates = [];
                $s_time = strtotime($start_of_month);
                $e_time = strtotime($end_of_month);
                while ($s_time <= $e_time) {
                    $this_month_dates[] = date('Y-m-d', $s_time);
                    $s_time = strtotime('+1 day', $s_time);
                }

                $last_month_dates = [];
                $s_time_last_month = strtotime($start_of_last_month);
                $e_time_last_month = strtotime($end_of_last_month);
                while ($s_time_last_month <= $e_time_last_month) {
                    $last_month_dates[] = date('Y-m-d', $s_time_last_month);
                    $s_time_last_month = strtotime('+1 day', $s_time_last_month);
                }

                $chart_where = "is_delete =0 and create_time BETWEEN '".date('Y-m-d 00:00:00', strtotime($start_of_last_month))."' and '".date('Y-m-d 23:59:59', strtotime($end_of_month))."'";
                $chart_sql = <<<SQL
                            SELECT 
                                date_format(create_time,'%Y-%m-%d') as date,
                                -- 订单数量
                                count(id) AS order_num,
                                -- 支付金额
                                SUM(principal+ difference_amount + mer_commission + add_comment_commission) AS order_amount
                            FROM 
                                ya_shop_order
                            where 
                                  {$chart_where}
                            GROUP BY date_format(create_time,'%Y-%m-%d')
                            SQL;
                $chart_list = Db::query($chart_sql);
                $of_month_nums=[];
                $of_month_amounts=[];
                $last_month_nums=[];
                $last_month_amounts=[];
                foreach ($last_month_dates as $k => $v) {
                    $last_month_nums[$k] = 0;
                    $last_month_amounts[$k] = 0;
                    foreach ($chart_list as $key=>$val){
                        if($val['date'] == $v){
                            $last_month_nums[$k] = $val['order_num'];
                            $last_month_amounts[$k] = $val['order_amount'];
                            break;
                        }
                    }
                }
                foreach ($this_month_dates as $k => $v) {
                    $of_month_nums[$k] = 0;
                    $of_month_amounts[$k] = 0;
                    foreach ($chart_list as $key=>$val){
                        if($val['date'] == $v){
                            $of_month_nums[$k] = $val['order_num'];
                            $of_month_amounts[$k] = $val['order_amount'];
                            break;
                        }
                    }
                }
                $series = [
                    ['name'=> '本月金额',
                        'type'=> 'bar',
                        'yAxisIndex'=> 0, // 使用第一个 y 轴（金额）
                        'data'=> $of_month_amounts,
                        'itemStyle'=> [
                            'color'=> '#50D899'
                        ]
                    ],
                    ['name'=> '上月金额',
                        'type'=> 'bar',
                        'yAxisIndex'=> 0, // 使用第一个 y 轴（金额）
                        'data'=> $last_month_amounts,
                        'itemStyle'=> [
                            'color'=> '#3EB2F6'
                        ]
                    ],
                    [
                        'name'=> '本月订单数',
                        'type'=> 'line',
                        'yAxisIndex'=> 1, // 使用第二个 y 轴（订单数）
                        'data'=> $of_month_nums, // 上月订单数
                        'smooth'=> true,
                        'lineStyle'=> [
                            'color'=> '#7CDFB2'
                        ]
                    ],
                    [
                        'name'=> '上月订单数',
                        'type'=> 'line',
                        'yAxisIndex'=> 1, // 使用第二个 y 轴（订单数）
                        'data'=> $last_month_nums, // 上月订单数
                        'smooth'=> true,
                        'lineStyle'=> [
                            'color'=> '#8FD0F8'
                        ]
                    ]
                ];
                $legend = array_column($series, 'name');
                for($i=1;$i<=31;$i++){
                    $xAxis[] = $i;
                }
                break;
            case 'year':
                // 获取今年和去年月份
                $this_year_months = [];
                $last_year_months = [];

                for ($i = 0; $i < 12; $i++) {
                    // 获取今年1月到12月的每个月份
                    $this_year_months[] = date('Y-m', strtotime("{$i} month", strtotime('first day of January this year')));

                    // 获取去年1月到12月的每个月份
                    $last_year_months[] = date('Y-m', strtotime("{$i} month", strtotime('first day of January last year')));
                }
                $chart_where = "is_delete =0 and create_time BETWEEN '".date('Y-m-01 00:00:00', strtotime($last_year_months[0]))."' and '".date('Y-m-31 23:59:59', strtotime($this_year_months[11]))."'";
                $chart_sql = <<<SQL
                            SELECT 
                                date_format(create_time,'%Y-%m') as date,
                                -- 订单数量
                                count(id) AS order_num,
                                -- 支付金额
                                SUM(principal+ difference_amount + mer_commission + add_comment_commission) AS order_amount
                            FROM 
                                ya_shop_order
                            where 
                                  {$chart_where}
                            GROUP BY date_format(create_time,'%Y-%m')
                            SQL;
                $chart_list = Db::query($chart_sql);
                $of_year_nums=[];
                $of_year_amounts=[];
                $last_year_nums=[];
                $last_year_amounts=[];
                foreach ($last_year_months as $k => $v) {
                    $last_year_nums[$k] = 0;
                    $last_year_amounts[$k] = 0;
                    foreach ($chart_list as $key=>$val){
                        if($val['date'] == $v){
                            $last_year_nums[$k] = $val['order_num'];
                            $last_year_amounts[$k] = $val['order_amount'];
                            break;
                        }
                    }
                }
                foreach ($this_year_months as $k => $v) {
                    $of_year_nums[$k] = 0;
                    $of_year_amounts[$k] = 0;
                    foreach ($chart_list as $key=>$val){
                        if($val['date'] == $v){
                            $of_year_nums[$k] = $val['order_num'];
                            $of_year_amounts[$k] = $val['order_amount'];
                            break;
                        }
                    }
                }
                $series = [
                    ['name'=> '本年金额',
                        'type'=> 'bar',
                        'yAxisIndex'=> 0, // 使用第一个 y 轴（金额）
                        'data'=> $of_year_amounts,
                        'itemStyle'=> [
                            'color'=> '#50D899'
                        ]
                    ],
                    ['name'=> '去年金额',
                        'type'=> 'bar',
                        'yAxisIndex'=> 0, // 使用第一个 y 轴（金额）
                        'data'=> $last_year_amounts,
                        'itemStyle'=> [
                            'color'=> '#3EB2F6'
                        ]
                    ],
                    [
                        'name'=> '本年订单数',
                        'type'=> 'line',
                        'yAxisIndex'=> 1, // 使用第二个 y 轴（订单数）
                        'data'=> $of_year_nums, // 上年订单数
                        'smooth'=> true,
                        'lineStyle'=> [
                            'color'=> '#7CDFB2'
                        ]
                    ],
                    [
                        'name'=> '去年订单数',
                        'type'=> 'line',
                        'yAxisIndex'=> 1, // 使用第二个 y 轴（订单数）
                        'data'=> $last_year_nums, // 上年订单数
                        'smooth'=> true,
                        'lineStyle'=> [
                            'color'=> '#8FD0F8'
                        ]
                    ]
                ];
                $legend = array_column($series, 'name');
                $xAxis =['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
                break;
        }
        return compact('legend','xAxis','series');
    }
    /**
     * 商家端首页数据统计
     * @Author: 易军辉
     * @DateTime:2024-11-01 17:07
     * @param $where
     */
    public static function dashboardStatistics($where=[])
    {
        /***************************组装条件***********************************************/
        $where_sql = "";//平台佣金条件
        $where_sql1 = "";//成交订单条件
        $where_sql2 = "";//退款订单条件
        $bill_where = [];
        $sta_date = date('Y-m-d 00:00:00', strtotime('-29 days'));
        $end_date = date('Y-m-d 23:59:59');
        foreach ($where as $key=>$val){
            $where_sql .=" and ";
            $where_sql1 .=" and ";
            $where_sql2 .=" and ";
            if($val[0] == 'platform_ids' && isset($val[2])) {
                $where_sql .= "store_platform_id in(" . implode(',', SettingStorePlatformModel::handleTaobaoIds($val[2])) . ")";
                $where_sql1 .= "store_platform_id in(" . implode(',', SettingStorePlatformModel::handleTaobaoIds($val[2])) . ")";
                $where_sql2 .= "store_platform_id in(" . implode(',', SettingStorePlatformModel::handleTaobaoIds($val[2])) . ")";
            }else if($val[0] == 'create_time'){//筛选时间
                if($val[1] == '>='){
                    $sta_date=$val[2];
                }else if($val[1] == '<='){
                    $end_date=$val[2];
                }
                array_push($bill_where,$val);
                $where_sql .=" create_time ".$val[1]." '".$val[2]."' ";
                $where_sql1 .=" ship_time ".$val[1]." '".$val[2]."' ";
                $where_sql2 .=" revoke_time ".$val[1]." '".$val[2]."' ";
            }else if(is_array($val[2])) {
                $where_sql .= $val[0] . " " . $val[1] . "(" . implode(',', $val[2]) . ")";
            }else if($val[1] == 'is'){
                $where_sql .=$val[0]." ".$val[1]." ".$val[2];
            }else{
                $where_sql .=$val[0]." ".$val[1]." '".$val[2]."' ";
            }
        }
        $order_where = " is_delete = 0 ";
        $mer_id = mer_id();
        if($mer_id>0){
            $order_where .=" AND merchant_id = ".$mer_id;
            $bill_where[] = ['mer_id','=',$mer_id];
        }
        $status_0 = ShopOrderModel::getStatus('o_listing',1);
        $status_1 = ShopOrderModel::getStatus('o_select',1);
        $status_2 = ShopOrderModel::getStatus('o_taking',1);
        $status_3 = ShopOrderModel::getStatus('o_operation',1);
        $status_4 = ShopOrderModel::getStatus('o_delivery',1);
        $status_5 = ShopOrderModel::getStatus('o_evaluate',1);
        $status_6 = ShopOrderModel::getStatus('o_auth',1);
        $status_7 = ShopOrderModel::getStatus('o_success',1);
        $status_9 = ShopOrderModel::getStatus('o_stop',1);
        $status_10 = ShopOrderModel::getStatus('o_revoke',1);
        $sql = <<<SQL
                SELECT 
                    -- 待付款
                SUM(CASE WHEN `status` = {$status_3} THEN 1 ELSE 0 END) AS o_operation,
                    -- 待发货
                SUM(CASE WHEN `status` = {$status_4} THEN 1 ELSE 0 END) AS o_delivery,
                    -- 金额异常
                SUM(CASE WHEN `status` = {$status_4} AND actual_amount > 0 AND actual_amount != principal THEN 1 ELSE 0 END) AS amount_error,
                    -- 评价待回复
                SUM(CASE WHEN `status` = {$status_6} THEN 1 ELSE 0 END) AS o_auth,
                    -- 活动库存
                SUM(CASE WHEN `status` IN ({$status_0}, {$status_1}, {$status_2}) THEN 1 ELSE 0 END) AS activity,
                    -- 申述中
                SUM(CASE WHEN `status` = {$status_9} THEN 1 ELSE 0 END) AS o_stop,
                    -- 成交金额
                SUM(CASE WHEN `status` IN ({$status_5}, {$status_6}, {$status_7}) {$where_sql1} THEN actual_amount  ELSE 0 END) AS success_amount,
                    -- 成交订单量
                SUM(CASE WHEN `status` IN ({$status_5}, {$status_6}, {$status_7}) {$where_sql1} THEN 1 ELSE 0 END) AS o_success,
                    -- 退款金额
                SUM(CASE WHEN `status` = {$status_10} {$where_sql2} THEN principal+ difference_amount + mer_commission + add_comment_commission ELSE 0 END) AS revoke_amount,
                    -- 退款订单量
                SUM(CASE WHEN `status` = {$status_10} {$where_sql2} THEN 1 ELSE 0 END) AS o_revoke,
                    -- 平台佣金
                SUM(CASE WHEN `status` IN ({$status_5}, {$status_6}, {$status_7}) {$where_sql1} THEN mer_commission + add_comment_commission ELSE 0 END) AS commission_amount
            FROM 
                ya_shop_order
            where 
                 {$order_where}
            SQL;
        $statistics = Db::query($sql);
        $statistics = $statistics[0];
        //查询充值金额
        $statistics['recharge_amount'] = Db::name('merchant_bill')
            ->where('is_delete',0)
            ->where('type',MerchantBillModel::getType('RECHARGE',1))
            ->where('principal','>',0)
            ->where($bill_where)
            ->sum('principal');
        $statistics['recharge_amount'] = number_format($statistics['recharge_amount'], 2, '.', '');
        /*******************************订单数量、支付金额、退款金额折线统计图**********************************/
        $s_time = strtotime(date('Y-m-d', strtotime($sta_date)));
        $e_time = strtotime(date('Y-m-d', strtotime($end_date)));
        $dates = [];
        while ($s_time <= $e_time) {
            $dates[] = date('Y-m-d', $s_time);
            $s_time = strtotime('next day', $s_time);
        }
        $chart_where = $order_where." and create_time>='".$sta_date."' and create_time<='".$end_date."'";
        $chart_sql = <<<SQL
                SELECT 
                        date_format(create_time,'%Y-%m-%d') as date,
                        -- 订单数量
                    count(id) AS o_success,
                        -- 支付金额
                    SUM(CASE WHEN `status` < {$status_10} THEN principal+ difference_amount + mer_commission + add_comment_commission ELSE 0 END) AS success_amount,
                        -- 退款金额
                    SUM(CASE WHEN `status` = {$status_10} THEN principal+ difference_amount + mer_commission + add_comment_commission ELSE 0 END) AS revoke_amount
                FROM 
                    ya_shop_order
                where 
                      {$chart_where}
                GROUP BY date_format(create_time,'%Y-%m-%d')
                SQL;
        $chart_list = Db::query($chart_sql);
        $order_total = [];
        $success_total = [];
        $revoke_total = [];
        foreach ($dates as $k => $v) {
            $order_total[$k] = 0;
            $success_total[$k] = 0;
            $revoke_total[$k] = 0;
            foreach ($chart_list as $key=>$val){
                if($val['date'] == $v){
                    $order_total[$k] = $val['o_success'];
                    $success_total[$k] = $val['success_amount'];
                    $revoke_total[$k] = $val['revoke_amount'];
                    break;
                }
            }
        }
        $series = [
            ['name' => '订单数量', 'type' => 'line', 'data' => $order_total, 'label' => ['show' => true, 'position' => 'top']],
            ['name' => '支付金额', 'type' => 'line', 'data' => $success_total, 'label' => ['show' => true, 'position' => 'top']],
            ['name' => '退款金额', 'type' => 'line', 'data' => $revoke_total, 'label' => ['show' => true, 'position' => 'top']],
        ];
        $legend = array_column($series, 'name');
        $statistics['chart'] = [
            'legend'=>$legend,
            'series'=>$series,
            'title'=>'数据统计',
            'type'=>'day',
            'xAxis'=>$dates
        ];
        return $statistics;
    }
    /**
     * 根据买家查询订单数量
     * @Author: 易军辉
     * @DateTime:2024-09-20 19:25
     * @param $member_id
     * @return array
     * @throws \think\db\exception\DbException
     */
    public static function getStatusNumByMember($member_id=0){
        $where = " where is_delete=0 and member_id=".$member_id;
        //根据状态查询数量
        $status_num = Db::query("SELECT status,count(id) as num from ya_shop_order ".$where." GROUP BY status");
        $status_nums = array();
        //订单总数
        $status_nums['all'] = Db::name('shop_order')
            ->where('is_delete',0)
            ->where('member_id',$member_id)
            ->count();
        //待追评数量
        $status_nums['o_dzp'] = Db::name('shop_order_comment')
            ->where('is_delete',0)
            ->where('comment_status',3)
            ->where('status',1)
            ->where('member_id',$member_id)
            ->count();
        foreach (ShopOrderModel::STATUS as $k => $v) {
            $status_nums[$v['code']] =0;
            foreach ($status_num as $k1 => $v1) {
                if($v1['status'] == $v['value']) {
                    $status_nums[$v['code']] = $v1['num'];
                    break;
                }
            }
        }
        return $status_nums;
    }



    /**
     * 查询商家返款订单数量
     * @Author: 易军辉
     * @DateTime:2024-07-16 15:18
     * @return array
     * @throws \think\db\exception\DbException
     */
    public static function getMerRefundStatusNum(){
        $merchantId = mer_id();
        $where = " where is_delete=0";
        if($merchantId>0){
            $where .=" and merchant_id=".$merchantId;
        }
        //商家返款
        $setting_refund_id = SettingRefundModel::getRefundType(SettingRefundModel::SJFK,1);
        if($setting_refund_id){
            $where .=" and setting_refund_id=".$setting_refund_id;
        }
        //订单状态
        $where .=" and status in(".
//            ShopOrderModel::getStatus('o_delivery',1).",".
            ShopOrderModel::getStatus('o_evaluate',1).",".
            ShopOrderModel::getStatus('o_auth',1).",".
            ShopOrderModel::getStatus('o_success',1)
            .") ";
        //根据状态查询数量
        $status_num = Db::query("SELECT mer_refund_status,count(id) as num from ya_shop_order ".$where." GROUP BY mer_refund_status");
        $status_nums = array();
        foreach (ShopOrderModel::REFUND_STATUS as $k => $v) {
            $status_nums[$v['code']] =0;
            foreach ($status_num as $k1 => $v1) {
                if($v1['mer_refund_status'] == $v['value']) {
                    $status_nums[$v['code']] = $v1['num'];
                    break;
                }
            }
        }
        return $status_nums;
    }

    /**
     * 订单管理信息
     * @Author: 易军辉
     * @DateTime:2024-09-02 17:46
     * @param $where 条件
     * @param $field 查询字段
     * @param $exce 是否提示报错
     * @param $is_mobile 是否为移动端
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function info($where,$field="", $exce = true,$is_mobile=false)
    {
        if(!$where){
            return [];
        }
        if (empty($field)) {
            $field = '
        platform.title as platform_title,
        platform.image_id as platform_image_id,
        type.title as type_title,
        shop.title as shop_title,
        refund.title as refund_title,
        goods.id as goods_id,
        goods.goods_title,
        goods.image_id as goods_image_id,
        goods.goods_spec,
        goods.goods_type,
        goods.order_price,
        goods.activity_price,
        product.h_pay_time,
        product.c_sort_type,
        product.c_pay_num,
        product.c_start_price,
        product.c_end_price,
        product.c_region_id,
        product.c_order_remark,
        product.c_subject,
        product.e_revoke_time,
        product.remark_images,
        product.remark as product_remark,
        enter.comment_type,
        enter.enter_type,
        enter.keyword as enter_keyword,
        enter.qr_image_id,
        enter.comment_image_id,
        enter.comment_vido_id,
        enter.order_num as enter_order_num,
        enter.spec as enter_spec,
        enter.content as enter_content,
        account.consignee as ac_consignee,
        account.phone as ac_phone,
        account.region_id as ac_region_id,
        account.address as ac_address,
        account.accname,
        a.*';
        }
        $sql = self::getListSql($where,[],$field);
        $list =  Db::query($sql);
        $merchantId = mer_id();
        //查询图片路径
        foreach ($list as $key=>$item) {
            //店铺图片
            $list[$key]['platform_image_url'] = "";
            if(isset($item['platform_code']) && $item['platform_code'] == SettingStorePlatformModel::CODE_TM){
                $platform = SettingStorePlatformModel::getPlatform(SettingStorePlatformModel::CODE_TB,4);
                if($platform){
                    $list[$key]['platform_title'] =$platform['title'];
                    $file = FileService::info($platform['image_id']);
                    if($file && isset($file['file_url'])){
                        $list[$key]['platform_image_url'] =$file['file_url'];
                    }
                }
            }else if($item['platform_image_id']){
                $file = FileService::info($item['platform_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['platform_image_url'] =$file['file_url'];
                }
            }
            //订单状态
            if(array_key_exists('status', $item)){
                $list[$key]['status_title'] = ShopOrderModel::getStatus($item['status'],2);
            }

            //评论类型
            if(isset($item['comment_type'])){
                $list[$key]['comment_type_str'] = SettingPriceRangeModel::getCommentType($item['comment_type'],1);
            }
            //进店方式
            if(isset($item['enter_type'])){
                $list[$key]['enter_type_str'] = SettingPriceRangeModel::getEnterType($item['enter_type'],1);
            }
            //二维码图片
            $list[$key]['qr_image_url'] ="";
            if(isset($item['qr_image_id'])){
                $qr_file = MerchantFileService::info($item['qr_image_id']);
                if($qr_file && isset($qr_file['file_url'])){
                    $list[$key]['qr_image_url'] =$qr_file['file_url'];
                }
            }
            //好评视频
            $list[$key]['comment_vido_url'] ="";
            if(isset($item['comment_vido_id'])){
                $vido_file = MerchantFileService::info($item['comment_vido_id']);
                if($vido_file && isset($vido_file['file_url'])){
                    $list[$key]['comment_vido_url'] =$vido_file['file_url'];
                }
            }
            //好评图片
            if(isset($item['comment_image_id'])){
                $files = Db::name('merchant_file')
                    ->where('is_disable',0)
                    ->where('is_delete',0)
                    ->where('file_id','in',explode(',',$item['comment_image_id']))
                    ->when($merchantId>0, function($query) use ($merchantId) {
                        $query->where('mer_id', $merchantId);
                    })
                    ->select()
                    ->toArray();
                foreach ($files as $k=>$v){
                    $files[$k]['file_url'] = SettingService::fileUrl($v);
                }
                $list[$key]['comment_image_ids'] =$files;
            }else{
                $list[$key]['comment_image_ids'] =[];
            }
            //做单图
            $list[$key]['screenshot_image_url'] ="";
            if(isset($item['screenshot_image_id'])){
                $file = FileService::info($item['screenshot_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['screenshot_image_url'] =$file['file_url'];
                }
            }
            //物流截图
            $list[$key]['logistics_image_url'] ="";
            if(isset($item['logistics_image_id'])){
                $file = FileService::info($item['logistics_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['logistics_image_url'] =$file['file_url'];
                }
            }
            //物流截图
            $list[$key]['evaluate_image_url'] ="";
            if(isset($item['evaluate_image_id'])){
                $file = FileService::info($item['evaluate_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['evaluate_image_url'] =$file['file_url'];
                }
            }
            //商品所在地
            $list[$key]['c_region_str'] ="";
            if(isset($item['c_region_id'])){
                $region = RegionService::info($item['c_region_id']);
                if(isset($region['region_fullname'])){
                    $list[$key]['c_region_str'] =$region['region_fullname'];
                }
            }
            //放单计划
            $list[$key]['creat_order_plan'] =Db::name('shop_product_release')->where(['shop_product_id' => $item['shop_product_id']])->select()->toArray();
            //附加要求
            if(isset($item['shop_product_price_ids'])){
                $list[$key]['shop_product_price'] =Db::name('shop_product_price')->where('id','in',explode(',', $item['shop_product_price_ids']))->order('type','asc')->select()->toArray();
            }
            //备注图片
            if(isset($item['remark_images'])){
                $files = Db::name('merchant_file')
                    ->where('is_disable',0)
                    ->where('is_delete',0)
                    ->where('file_id','in',explode(',',$item['remark_images']))
                    ->when($merchantId>0, function($query) use ($merchantId) {
                        $query->where('mer_id', $merchantId);
                    })
                    ->select()
                    ->toArray();
                foreach ($files as $k=>$v){
                    $files[$k]['file_url'] = SettingService::fileUrl($v);
                }
                $list[$key]['remark_images'] =$files;
            }else{
                $list[$key]['remark_images'] =[];
            }
            //订单日志
            if(!$is_mobile) {
                $list[$key]['log_list'] = Db::name('shop_order_log')
                    ->where('is_delete', 0)
                    ->where('shop_order_id', $item['id'])
                    ->select();
            }
            //收货地址
            $item['ac_region_str'] = "";
            if(isset($item['ac_region_id'])){
                $region = RegionService::info($item['ac_region_id']);
                if(isset($region['region_fullname'])){
                    $list[$key]['ac_region_str']  =$region['region_fullname'];
                }
            }
            //查询发布评论/追加评论
            $list[$key]['order_comment2'] = null;
            $list[$key]['order_comment3'] = null;
            $list[$key]['order_comment_status2'] = 0;
            $list[$key]['order_comment_status3'] = 0;
            if($is_mobile){
                $order_comments = Db::name('shop_order_comment')->where('is_delete',0)->where('shop_order_id',$item['id'])->select()->toArray();
                foreach ($order_comments as $k=>$v){
                    //好评视频
                    $v['comment_vido_url'] =null;
                    if($v['comment_vido_id']){
                        $file = MerchantFileService::info($v['comment_vido_id']);
                        if($file && isset($file['file_url'])){
                            $v['comment_vido_url'] =$file['file_url'];
                        }
                    }
                    //好评图片
                    if($v['comment_image_id']){
                        $files = Db::name('merchant_file')
                            ->where('is_disable',0)
                            ->where('is_delete',0)
                            ->where('file_id','in',explode(',',$v['comment_image_id']))
                            ->when($merchantId>0, function($query) use ($merchantId) {
                                $query->where('mer_id', $merchantId);
                            })
                            ->select()
                            ->toArray();
                        foreach ($files as $fk=>$fv){
                            $files[$fk]['file_url'] = SettingService::fileUrl($fv);
                        }
                        $v['comment_image_id'] =$files;
                    }else{
                        $v['comment_image_id'] =[];
                    }
                    if($v['evaluate_image_id']){
                        $file = FileService::info($v['evaluate_image_id']);
                        if($file && isset($file['file_url'])){
                            $v['evaluate_image_url'] =$file['file_url'];
                        }
                    }
                    //发布评价整合在正常评价流程中
                    if($v['comment_status'] == 2 && array_key_exists('comment_type', $item) && $item['comment_type'] ==0){
                        $list[$key]['comment_type'] =$v['comment_type'];
                        $list[$key]['comment_image_ids'] = $v['comment_image_id'];
                        $list[$key]['comment_vido_url'] = $v['comment_vido_url'];
                        $list[$key]['enter_content'] = $v['content'];
                    }
                    $list[$key]['order_comment'.$v['comment_status']] = $v;
                    $list[$key]['order_comment_status'.$v['comment_status']] =$v['status'];
                }
            }
            if(!$is_mobile){
                //利润计算
                $list[$key]['profit'] =self::profitHandle($item);
            }
        }
        $info = $list[0];
        if (empty($info)) {
            if ($exce) {
                exception('订单不存在');
            }
            return [];
        }
        //查询商品信息
        $goods = Db::name('shop_product_goods')->alias('a')
            ->leftJoin('setting_store_type','a.setting_store_type_id = setting_store_type.id')
            ->where('shop_product_id',$info['shop_product_id'])
            ->field('a.*,setting_store_type.title as goods_type')
            ->select()
            ->toArray();
        foreach ($goods as $key=>$val) {
            if($val['image_id']){
                $file = MerchantFileService::info($val['image_id']);
                if($file && isset($file['file_url'])){
                    $goods[$key]['image_url'] = $file['file_url'];
                }
                if($is_mobile && array_key_exists('status', $info) && $info['status']== ShopOrderModel::getStatus('o_operation',1)){
                    // 查找最后一个点的位置
                    $lastDotPosition = strrpos($file['file_path'], '.');
                    $newFilePath = substr($file['file_path'], 0, $lastDotPosition) . '_pixelated' . substr($file['file_path'], $lastDotPosition);
                    $new_file_path = self::pixelateImage($file['file_path'],$newFilePath,30);
                    if($new_file_path){
                        $goods[$key]['image_url'] = file_url($new_file_path);
                    }
                }
            }
            if($val['activity_image_id']){
                $file1 = MerchantFileService::info($val['activity_image_id']);
                if($file1 && isset($file1['file_url'])){
                    $goods[$key]['activity_image_url'] = $file1['file_url'];
                }
            }
        }
        $info['goods_list'] = $goods;
        //店铺名称处理
        if (isset($info['shop_title']) && $is_mobile && array_key_exists('status', $info) && $info['status']== ShopOrderModel::getStatus('o_operation',1)){
            $info['shop_title'] = self::hideMiddle($info['shop_title']);
        }
        //宝贝详情问答处理
        if (isset($info['c_subject']) && $is_mobile){
            $info['c_subject'] = self::hideSpace($info['c_subject']);
        }
        //买家操作订单内容
        if(
            array_key_exists('id',$info)
            && array_key_exists('merchant_id',$info)
            && array_key_exists('merchant_shop_id',$info)
            && array_key_exists('member_id',$info)
            && array_key_exists('member_account_id',$info)
        ){
            $info['order_answer'] =Db::name('shop_order_answer')->where('shop_order_id',$info['id'])->find();
            if(!$info['order_answer']){
                $info['order_answer'] =[
                    'shop_order_id'=>$info['id'],//订单ID
                    'merchant_id'=>$info['merchant_id'],//商家ID
                    'merchant_shop_id'=>$info['merchant_shop_id'],//店铺ID
                    'member_id'=>$info['member_id'],//接单人id
                    'member_account_id'=>$info['member_account_id'],//接单人账号ID
                    'keyword'=>null,//关键词链接
                    'goods_compare1'=>null,//货比商品1链接
                    'goods_compare2'=>null,//货比商品2链接
                    'goods_compare3'=>null,//货比商品3链接
                    'goods_url0'=>null,//主商品链接
                    'goods_url1'=>null,//附加商品链接1
                    'goods_url2'=>null,//附加商品链接2
                    'goods_url3'=>null,//附加商品链接3
                    'goods_url4'=>null,//附加商品链接4
                    'goods_url5'=>null,//附加商品链接5
                    'goods_browse1'=>null,//浏览附商品链接1
                    'goods_browse2'=>null,//浏览附商品链接2
                    'shop_title'=>null,//店铺名称
                    'c_subject'=>null,//商品详情问答
                    'live_room_url'=>null,//直播间链接
                    'pay_image_id'=>null,//付款截图
                    'pay_image_url'=>null,//付款截图
                    'other'=>null,//其它信息
                ];
            }else{
                if($info['order_answer']['other']){
                    $info['order_answer']['other'] = json_decode($info['order_answer']['other'], true);
                }
                if($info['order_answer']['pay_image_id']){
                    $file = FileService::info($info['order_answer']['pay_image_id']);
                    if($file && isset($file['file_url'])){
                        $info['order_answer']['pay_image_url'] =$file['file_url'];
                    }
                }
            }
        }
        //增值服务附加要求处理
        if(
            array_key_exists('shop_product_id',$info)
            && array_key_exists('setting_price_range_ids',$info)
        ) {
            $range_codes = SettingPriceRangeModel::RANGE_CODES;
            $range_codes[] = 'Self_selection';//商家自选买号过滤掉
            $info = self::getPriceCondition($info, $range_codes);
        }
        //平台补贴商品返利
        if(isset($info['shop_product_type_code']) && $info['shop_product_type_code']=='PTBT'){
            $info['rebate'] = bcadd($info['principal'],$info['commission'],2);
            //到手价
            if(array_key_exists('status', $info) && $info['status']> ShopOrderModel::getStatus('o_operation',1)){
                $info['received_price'] = bcsub($info['advance_amount'], $info['rebate'],2);
            }
        }

        return $info;
    }
    /**
     * 查询增值条件
     * @Author: 易军辉
     * @DateTime:2024-08-26 17:13
     * @param $info 订单信息
     * @param $range_codes 过滤掉的增值code
     */
    private static function getPriceCondition($info,$range_codes)
    {
        $info['price_condition_code'] = [];//把所有条件通过code为键存储一次
        $shop_product_id = $info['shop_product_id'];//商品表id
        $other = [];//买家提交信息字段组建
        if(!$shop_product_id){
            return [];
        }
        //需要过滤掉的编码
        $quoted_range_codes = array_map(function($code) { return "'$code'"; }, $range_codes);
        $range_code_str = implode(',', $quoted_range_codes);
        //处理没有勾选增值条件
        $setting_price_range_ids = $info['setting_price_range_ids'];
        if(!$setting_price_range_ids){
            $setting_price_range_ids = 0;
        }
        $sql = <<<SQL
            SELECT 
                spi.setting_price_range_id,
                spi.setting_price_condition_type,
                spi.setting_price_range_code,
                spi.mer_describe,
                spi.condition_value,
                spr.user_describe,
                spr.user_help_code
            from ya_shop_product_increment as spi
            LEFT JOIN ya_setting_price_range as spr on spi.setting_price_range_id=spr.id
            where spi.shop_product_id ={$shop_product_id} 
            and spi.setting_price_range_id in({$setting_price_range_ids}) 
            and spi.setting_price_range_code not in({$range_code_str})
            and spr.is_disable=0
            and spr.is_delete=0
            GROUP BY spi.setting_price_range_id
            ORDER BY spr.sort asc
        SQL;
//        echo $sql;exit();
        $list = Db::query($sql);
        //查询增值条件
        $conditions =[];
        if(count($list)>0){
            $conditions = SettingPriceConditionModel::whereIn('setting_price_range_id',array_column($list,'setting_price_range_id'))->select()->toArray();
        }
        foreach ($list as $key=>$item){
            $list[$key]['radio_type'] =0;//单选项内容：0、无 1、需要截图 2、无需截图 3、分钟限制 4、需勾选确认
            $filed_key = 'price_range_'.$item['setting_price_range_id'];
            /****************************************增值条件类型：0、单选  1、多选 2、文本框  3、时间控件 4、地区***************************************/
            $list[$key]['setting_price_condition_type'] =[];
            if(array_key_exists('setting_price_condition_type', $item) && $item['setting_price_condition_type']!=null && $item['setting_price_condition_type']!=""){
                // 将字符串数组转换为整数数组
                $list[$key]['setting_price_condition_type'] = array_map('intval', explode(",",$item['setting_price_condition_type']));
            }
            /***************************************需勾选确认*************************************/
            if($item['setting_price_range_code'] == 'Close_positive_reviews'){
                $list[$key]['radio_type'] =4;
                $other[$filed_key."_checked"] = false;
            }
            /***************************************商家选中值*************************************/
            $condition_value = json_decode($item['condition_value'], true);
            // 定义一个数组来存储分组结果
            $groupedResult = [];
            foreach ($conditions as $k=>$condition){
                if(in_array($condition['type'], $list[$key]['setting_price_condition_type']) && $item['setting_price_range_id'] == $condition['setting_price_range_id']){
                    /***************************************商家选中值处理*************************************/
                    // 获取 type 值
                    $type = $condition['type'];
                    $filed_name = 'price_range_'.$item['setting_price_range_id']."_".$type;
                    if($condition_value && array_key_exists($filed_name, $condition_value)){
                        $list[$key][$filed_name] =$condition_value[$filed_name];
                    }
                    //获取默认值
                    switch (intval($type)) {
                        case 0://单选
                            if(array_key_exists($filed_name, $condition_value) && $condition_value[$filed_name] == $condition['value']){
                                $list[$key][$filed_name.'_label'] = $condition['label'];
                                $condition['is_checked'] = true;
                                if(self::is_screenshot($condition['label'],1)){//需要截图
                                    $list[$key]['radio_type'] =1;
                                    $other[$filed_key."_image_id"] = null;
                                    $other[$filed_key."_image_url"] = null;
                                }else if(self::is_screenshot($condition['label'],2)){//无需截图
                                    $list[$key]['radio_type'] =2;
                                    $other[$filed_key."_checked"] = false;
                                }else if(strpos($condition['label'], '分钟') !== false){
                                    $list[$key]['radio_type'] =3;
                                    if(preg_match('/\d+(\.\d+)?/', $condition['label'], $matches)){
                                        $list[$key]['time'] =(int)$matches[0];//获取分钟数字
                                    }
                                }
                            }
                            break;
                        case 1://多选
                            if(array_key_exists($filed_name, $condition_value) && in_array($condition['value'],$list[$key][$filed_name])) {
                                $condition['is_checked'] = true;
                            }
                            break;
                    }
                    // 根据 type 分组
                    if (!isset($groupedResult[$type])) {
                        $groupedResult[$type] = [];
                    }
                    // 将 condition 添加到相应的 type 分组中
                    $groupedResult[$type][] = $condition;
                }
            }
            $list[$key]['condition'] =$groupedResult;
            $info['price_condition_code'][$item['setting_price_range_code']] = $list[$key];
        }
        $info['price_condition_list'] = $list;
        if(!$info['order_answer']['other']){
            $info['order_answer']['other'] = $other;
        }
        return $info;
    }

    /**
     * 是否需要截图判断
     * @Author: 易军辉
     * @DateTime:2024-09-07 15:23
     * @param $lable 条件名称
     * @param $is_screenshot 1:需要截图  2:无需截图
     */
    private static function is_screenshot($lable="",$is_screenshot=0)
    {
        switch ($is_screenshot){
            case 1:
                if(strpos($lable, '需要截图') !== false || (strpos($lable, '需截图') !== false && strpos($lable, '无需截图') === false)){
                    return true;
                }
                break;
            case 2:
                if(strpos($lable, '无需截图') !== false){
                    return true;
                }
                break;
        }
        return false;
    }
    /**
     * 店铺名称处理
     * @Author: 易军辉
     * @DateTime:2024-09-02 17:47
     * @param $str 店铺名称
     * @return mixed|string
     */
    private static function hideMiddle($str)
    {
        $length = mb_strlen($str); // 获取字符串长度，支持多字节字符

        // 小于3个字不需要隐藏
        if ($length < 3) {
            return $str;
        }

        // 如果字符串长度为3，只隐藏中间一个字
        if ($length == 3) {
            return mb_substr($str, 0, 1) . '*' . mb_substr($str, 2, 1);
        }

        // 对于长度大于3的情况，将中间3个字符替换成***
        $start = mb_substr($str, 0, floor(($length - 3) / 2)); // 前半部分
        $end = mb_substr($str, -ceil(($length - 3) / 2)); // 后半部分

        return $start . '***' . $end;
    }

    /**
     * 详情问答（间隔隐藏字符）
     * @Author: 易军辉
     * @DateTime:2024-09-07 19:54
     * @param $str
     * @param $type 1、从第二个字符开始隐藏  2、从第一个字符开始隐藏
     */
    private static function hideSpace($str,$type=1)
    {
        $result = preg_replace_callback('/.{1}/u', function ($matches)use($type) {
            static $i = 0;
            if($type==2){
                return ($i++ % 2 === 0) ? '*' : $matches[0];
            }else{
                return ($i++ % 2 === 0) ? $matches[0] : '*';
            }
        }, $str);
        return $result;
    }
    /**
     * 订单管理添加
     *
     * @param array $param 订单管理信息
     *
     * @return array|Exception
     */
    public static function add($param)
    {
        $model = new ShopOrderModel();
        $pk = $model->getPk();
        unset($param[$pk]);
        $param['create_uid']  = user_id();
        $param['create_time'] = datetime();
        $model->save($param);
        $id = $model->$pk;
        if (empty($id)) {
            exception();
        }
        $param[$pk] = $id;
        return $param;
    }
     /**
     * 订单管理修改
     *
     * @param int|array $ids   订单管理id
     * @param array     $param 订单管理信息
     *
     * @return array|Exception
     */
    public static function edit($ids, $param = [])
    {
        $model = new ShopOrderModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $param['update_uid']  = user_id();
        $param['update_time'] = datetime();
        $res = $model->where($pk, 'in', $ids)->update($param);
        if (empty($res)) {
            exception();
        }
        $param['ids'] = $ids;
        ShopOrderCache::del($ids);
        return $param;
    }
    /**
     * 订单管理删除
     *
     * @param array $ids  订单管理id
     * @param bool  $real 是否真实删除
     *
     * @return array|Exception
     */
    public static function dele($ids, $real = false)
    {
        $model = new ShopOrderModel();
        $pk = $model->getPk();
        if ($real) {
            $res = $model->where($pk, 'in', $ids)->delete();
        } else {
            $update = delete_update();
            $res = $model->where($pk, 'in', $ids)->update($update);
        }
        if (empty($res)) {
            exception();
        }
        $update['ids'] = $ids;
        ShopOrderCache::del($ids);
        return $update;
    }

    /**
     * 订单催评
     * @Author: 易军辉
     * @DateTime:2024-06-24 14:58
     * @param $ids
     * @param $real
     * @return array
     * @throws \think\Exception
     */
    public static function urge($ids)
    {
        // 获取当前日期的前3天和前1天的日期
        $three_days_ago = date('Y-m-d H:i:s', strtotime('-3 days'));
        $one_day_ago = date('Y-m-d H:i:s', strtotime('-1 day'));
        $list = Db::name('shop_order')
            ->alias('a')
            ->where('a.is_delete',0)
            ->where('a.merchant_id',mer_id())
            ->where('a.status',ShopOrderModel::getStatus('o_evaluate',1))
            ->where('a.id','in',$ids)
            ->where('a.ship_time','<=',$three_days_ago)
            ->field('a.id,a.member_id,a.member_account_id')
            ->select();
        $insert = [];
        $create_uid = mer_user_id(true);
        foreach ($list as $key=>$val){
            $urge = Db::name('shop_order_urge')
                ->where('shop_order_id',$val['id'])
                ->where('is_delete', 0)
                ->order('create_time','desc')
                ->field('id,create_time')
                ->find();
            if(!$urge || $urge['create_time']<=$one_day_ago){
                $insert[] = array(
                    'member_id'=>$val['member_id'],
                    'member_account_id'=>$val['member_account_id'],
                    'shop_order_id'=>$val['id'],
                    'create_uid'=>$create_uid,
                    'create_time'=>date('Y-m-d H:i:s'),
                );
            }
        }
        if($insert){
           $res = Db::name('shop_order_urge')->insertAll($insert);
        }else{
            exception('未查询到符合催评条件的订单');
        }
        return true;
    }


    /**
     * 查询订单日志
     * @param $id
     * @param $exce
     * @return void
     */
    public static function getLog($id)
    {
        $model = new ShopOrderLogModel();
        $list = $model->where('shop_order_id',$id)->where('is_delete',0)->select()->toArray();
        return $list;
    }

    /**
     * 生成增值服务ID（新增字段，完善内容）
     * @Author: 易军辉
     * @DateTime:2024-09-11 11:24
     */
    private static function create_setting_price_range_ids()
    {
        ini_set('max_execution_time', 0);
        $order_list = Db::name('shop_order')->where('is_delete',0)->whereNull('setting_price_range_ids')->field('id,shop_product_id,shop_product_price_ids,setting_price_range_ids')->select()->toArray();
        foreach ($order_list as $key=>$val){
            $product_price_ids = Db::name('shop_product_price')
                ->where('shop_product_id',$val['shop_product_id'])
                ->where('type','increment')
                ->whereIn('id',explode(",", $val['shop_product_price_ids']))
                ->column('data_id');
            //不完善，还需根据订单数量进行匹配
            $product_increment_ids = Db::name('shop_product_increment')
                ->where('shop_product_id',$val['shop_product_id'])
                ->when(count($product_price_ids)>0, function($query) use ($product_price_ids) {
                    $query->whereNotIn('setting_price_range_id',$product_price_ids);
                })
                ->column('setting_price_range_id');
            $ids = array_merge($product_price_ids,$product_increment_ids);
            if($ids){
                $res = Db::name('shop_order')->where('id',$val['id'])->update([
                    'setting_price_range_ids'=>implode(',',$ids)
                ]);
            }
        }
    }

    /**
     * 订单发货
     * @Author: 易军辉
     * @DateTime:2024-06-24 16:46
     * @param $ids
     */
    public static function shipping($ids)
    {
        $model = new ShopOrderModel();
        $pk = $model->getPk();
        $mer_id = mer_id();
        $list = $model
            ->where($pk, 'in', $ids)
            ->where('is_delete',0)
            ->where('is_appeal','<>',1)
            ->when($mer_id>0,function($query)use($mer_id){
                $query->where('merchant_id',$mer_id);
            })
            ->where('status',ShopOrderModel::getStatus('o_delivery',1))
            ->select();
        if (empty($list)) {
            exception('未查询到符合发货条件的订单');
        }
        $order_ids = array_column($list->toArray(),'id');
        Db::startTrans();
        try {
            //查询返款设置
            $setting = SystemSettingService::info('order_max_principal,order_principal_status,order_principal_time,order_commission_status,order_commission_time');
            //添加日志
            $log_data = [];
            foreach ($list as $key=>$val){
                $log_code = 'FFCG';
                $val->ship_uid = mer_user_id();
                $val->ship_time = date('Y-m-d H:i:s');
                $val->old_status = $val['status'];

                //浏览任务需要特殊处理，发货后直接改为完成状态
                if($val['shop_product_type_code'] == ShopProductTypeModel::LLRW){
                    $val->status = ShopOrderModel::getStatus('o_success',1);
                    $log_code = "DDWC";
                    //支付买家佣金
                    $commission_res = MemberService::income(
                        $val['member_id'],
                        $val['commission'],
                        0,
                        $val['commission'],
                        null,//订单佣金返款
                        $val['id'],
                        $val['member_account_id'],
                        '结算订单：'.$val['id'],
                        'PTBT'
                    );
                    $val->is_commission  =1;
                    $val->commission_time =date('Y-m-d H:i:s');
                    //给买家发送消息通知
                    MemberMessageService::add([
                        'title'=>MemberBillModel::getType('PTBT',2),
                        'content'=>'您的订单：'.$val['id'].'，'.$val['commission'].'元补贴已到账',
                        'member_id'=>$val['member_id'],
                        'data_id'=>$val['id'],
                    ]);
                    $pay_res = self::payPromotionFee($val);
                }else{
                    if($val['actual_amount']<=0){
                        exception('订单ID：'.$val['id']."，实付金额小于等于0，请检查");
                    }
                    $val->status = ShopOrderModel::getStatus('o_evaluate',1);
                    /***********************实付金额多退少补****************************/
//                    if($val['principal']!=$val['actual_amount'] && $val['difference_amount']==0) {
//                        $val->difference_amount = self::orderActualAmount($val);
//                    }
                    /********************判断是否在待评价时进行返款*********************************/
                    self::payMemberAmount($val,$setting);
                }
                //给买家发送消息通知
                MemberMessageService::add([
                    'title'=>'发货通知',
                    'content'=>'您的订单：'.$val['id'].'，商家已发货，请收货后再确认',
                    'member_id'=>$val['member_id'],
                    'data_id'=>$val['id'],
                ]);
                $log_data[] = array(
                    'merchant_id'=>$val['merchant_id'],
                    'shop_order_id'=>$val['id'],
                    'order_status'=>$val->status,
                    'code'=>$log_code,
                    'title'=>ShopOrderLogModel::getStatus($log_code,2),
                    'create_uid'=>mer_user_id(),
                    'create_time'=>date('Y-m-d H:i:s'),
                );
                $save_res = $val->save();
            }
            if($log_data){
                $log_res = Db::name('shop_order_log')->insertAll($log_data);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        if (isset($errmsg)) {
            exception($errmsg);
        }
        $param['ids'] = $order_ids;
        ShopOrderCache::del($ids);
        return $param;
    }

    /**
     * 实付金额多退少补
     * @Author: 易军辉
     * @DateTime:2024-09-11 12:23
     * @param $order 订单信息
     * @param $exce 商家补款异常是否报错
     */
    private static function orderActualAmount($order,$exce = true)
    {
        $difference = 0;
        //退款
        if($order['principal']>$order['actual_amount']){
            //退款金额
            $difference = bcsub($order['principal'], $order['actual_amount'],2);
            $consumption_res = MerchantService::refund(
                $order['merchant_id'],
                $difference,
                $difference,
                0,
                '订单差价',
                $order['id'],
                $order['merchant_shop_id'],
                "订单ID：".$order['id']
            );
        }else if($order['principal']<$order['actual_amount']){
            $difference = bcsub($order['principal'], $order['actual_amount'],2);
            //补款
            $b_difference = bcsub($order['actual_amount'],$order['principal'],2);
            $consumption_res = MerchantService::consumption(
                $b_difference,
                $b_difference,
                0,
                '订单差价',
                $order['id'],
                $order['merchant_shop_id'],
                "订单ID：".$order['id'],
                $order['merchant_id'],
                $exce
            );
        }
        $res = Db::name('shop_order')->where('id',$order['id'])->update(['difference_amount'=>$difference]);
        if($res){
            return $difference;
        }
        return $difference;
    }
    /**
     * 订单审核
     * @Author: 易军辉
     * @DateTime:2024-06-25 09:31
     * @param $ids
     * @param $param
     */
    public static function auth($ids, $param = [])
    {
        $model = new ShopOrderModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $mer_id = mer_id();
        $list = $model
            ->where($pk, 'in', $ids)
            ->where('is_delete',0)
            ->where('is_appeal','<>',1)
            ->when($mer_id>0,function($query)use($mer_id){
                $query->where('merchant_id',$mer_id);
            })
            ->where('status',$model::getStatus('o_auth',1))
            ->select();
        if (count($list)<=0) {
            exception('未查询到符合审核条件的订单');
        }
        $order_ids = array_column($list->toArray(),'id');
        //审核用户
        $auth_uid = mer_user_id();
        if($auth_uid<=0){
            $auth_uid = user_id();
        }
        // 启动事务
        $model->startTrans();
        try {
            //查询返款设置
            $setting = SystemSettingService::info('order_max_principal,order_principal_status,order_principal_time,order_commission_status,order_commission_time');
            //添加日志
            $log_data = [];
            $shop_product_ids = [];
            foreach ($list as $k=>$v){
                $v->auth_time=datetime();
                $v->auth_uid=$auth_uid;
                switch (intval($param['auth_status'])){
                    case 1://审核通过
                        $v->old_status=$v->status;
                        $v->status=$model::getStatus('o_success',1);
                        $v->success_time=date('Y-m-d H:i:s');
                        $log_data[] = array(
                            'merchant_id'=>$v['merchant_id'],
                            'shop_order_id'=>$v['id'],
                            'order_status'=>$v->status,
                            'code'=>'DDWC',
                            'title'=>ShopOrderLogModel::getStatus('DDWC',2),
                            'create_uid'=>$auth_uid,
                            'create_time'=>date('Y-m-d H:i:s'),
                        );
                        /********************判断是否在完成时进行返款*********************************/
                        self::payMemberAmount($v,$setting);
                        array_push($shop_product_ids,$v['shop_product_id']);
                        break;
                    case 2://审核未通过
                        $v->old_status=$v->status;
                        $v->status=$model::getStatus('o_auth_error',1);
                        $v->auth_remark=$param['auth_msg'];
                        $log_data[] = array(
                            'merchant_id'=>$v['merchant_id'],
                            'shop_order_id'=>$v['id'],
                            'order_status'=>$v->status,
                            'code'=>'PJSHSB',
                            'title'=>ShopOrderLogModel::getStatus('PJSHSB',2),
                            'create_uid'=>$auth_uid,
                            'create_time'=>date('Y-m-d H:i:s'),
                        );
                        break;
                }
                /********************判断是否有发布评价处理*********************************/
                self::orderCommentHandle($v['id'],intval($param['auth_status']),$auth_uid,$param['auth_msg']);
                $v->save();
            }
            if($log_data){
                $log_res = Db::name('shop_order_log')->insertAll($log_data);
            }
            // 提交事务
            $model->commit();
            /********************处理商品状态*********************************/
            if(count($shop_product_ids)>0){
                ShopProductService::changeStatus($shop_product_ids);
            }
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }

        $param['ids'] = $order_ids;
        ShopOrderCache::del($order_ids);
        return $param;
    }

    /**
     * 超24小时自动发货、完成
     * @Author: 易军辉
     * @DateTime:2024-11-08 20:53
     * @return string
     */
    public static function orderAuthTime()
    {
        $status_4 = ShopOrderModel::getStatus('o_delivery',1);
        $status_6 = ShopOrderModel::getStatus('o_auth',1);
        $sql = <<<SQL
                SELECT 
                    GROUP_CONCAT(CASE WHEN a.`status` = {$status_4} AND TIMESTAMPDIFF(HOUR, a.operate_time, NOW()) > 12 THEN a.id END) AS delivery_ids,
                    GROUP_CONCAT(CASE WHEN a.`status` = {$status_6} AND TIMESTAMPDIFF(HOUR, a.evaluate_time, NOW()) > 12 THEN a.id END) AS auth_ids
                FROM ya_shop_order AS a
                WHERE 
                    a.is_delete = 0
                    AND a.`status` IN ({$status_4}, {$status_6})
            SQL;
        $list = Db::query($sql);

        $res="";
        foreach ($list as $key=>$val){
            if($val['delivery_ids']){//自动发货订单ids
                $delivery_ids = explode(",", $val['delivery_ids']);
                self::shipping($delivery_ids);
                $res .="订单超24小时自动发货".count($delivery_ids)."条，订单ID：".$val['delivery_ids'];
            }
            if($val['auth_ids']){//自动审核订单ids
                $auth_ids = explode(",", $val['auth_ids']);
                self::auth($auth_ids,['auth_status'=>1,'auth_msg'=>"订单超24小时自动完成"]);
                $res .="订单超24小时自动完成".count($auth_ids)."条，订单ID：".$val['auth_ids'];
            }
        }
        return $res;
    }

    /**
     * 查看是否有发布评价进行处理
     * @Author: 易军辉
     * @DateTime:2024-09-20 10:15
     * @param $order_id 订单状态
     * @param $auth_status 审核状态 1、审核通过 2、审核拒绝
     */
    private static function orderCommentHandle($order_id,$auth_status,$auth_uid=0,$auth_msg="")
    {
        $order_comment = Db::name('shop_order_comment')
            ->where('is_delete',0)
            ->where('shop_order_id',$order_id)
            ->where('status',2)
            ->where('comment_status',2)
            ->order(['create_time'=>'asc'])
            ->find();
        if($order_comment){
            $update = [
                'auth_time'=>datetime(),
                'auth_uid'=>$auth_uid
            ];
            switch ($auth_status) {
                case 1://审核通过
                    $update['status'] = ShopOrderCommentModel::getStatus('c_success',1);
                    /********************判断是否在完成时进行返款*********************************/
                    if($order_comment['member_id'] && $order_comment['member_account_id'] && $order_comment['commission']>0){
                        $commission_res = MemberService::income(
                            $order_comment['member_id'],
                            $order_comment['commission'],
                            0,
                            $order_comment['commission'],
                            null,//评价佣金返款
                            $order_comment['id'],
                            $order_comment['member_account_id'],
                            '结算订单：'.$order_comment['shop_order_id'],
                            'PTBT'
                        );
                        //给买家发送消息通知
                        MemberMessageService::add([
                            'title'=>MemberBillModel::getType('PTBT',2),
                            'content'=>"您的订单：".$order_id."，完成评论，补贴".$order_comment['commission']."元",
                            'member_id'=>$order_comment['member_id'],
                            'data_id'=>$order_id,
                        ]);
                        if($commission_res){
                            $update['is_member_pay'] =1;
                        }
                    }
                    $update['success_time'] =datetime();
                    break;
                case 2://审核拒绝
                    $update['status'] = ShopOrderCommentModel::getStatus('c_auth_error',1);
                    $update['auth_msg'] =$auth_msg;
                    break;
            }
            return Db::name('shop_order_comment')->where('id',$order_comment['id'])->update($update);
        }
        return false;
    }

    /**
     * 支付买家佣金和本金
     * @Author: 易军辉
     * @DateTime:2024-06-25 17:45
     * @param $order 订单信息
     * @param $setting 返款设置
     */
    private static function payMemberAmount($order,$setting){
        /******************************获取商家返款ID,商家返款，需要商家手动返给买家本金*****************************/
        $setting_refund_id = SettingRefundModel::getRefundType(SettingRefundModel::SJFK,1);
        if(!$order['member_id']){
            return false;
        }
        /******************************本金小于等于设置本金货返节点*****************************/
        if($setting['order_max_principal'] == 0 || $order['principal']<=$setting['order_max_principal']){
            /******************************本金*****************************/
            if(
                $order['is_principal'] == 0
                && $order['principal']>0
                && $order['actual_amount']>0
                && $setting['order_principal_status'] == ShopOrderModel::getStatus($order['status'],3)
                && $order['setting_refund_id']!=$setting_refund_id
            ){
                $is_execute = false;//是否满足本金发放条件
                switch ($order['status']){
                    case ShopOrderModel::getStatus('o_delivery',1)://待发货
                        //立即返款
                        if($setting['order_principal_time']<=0){
                            $is_execute = true;
                        }else if(
                            $order['operate_time']
                            && $setting['order_principal_time']>0
                            && hourCalculation($order['operate_time'],date('Y-m-d H:i:s'))>=$setting['order_principal_time']
                        ){
                            $is_execute = true;
                        }
                        break;
                    case ShopOrderModel::getStatus('o_evaluate',1)://待评价
                        //立即返款
                        if($setting['order_principal_time']<=0){
                            $is_execute = true;
                        }else if(
                            $order['ship_time']
                            && $setting['order_principal_time']>0
                            && hourCalculation($order['ship_time'],date('Y-m-d H:i:s'))>=$setting['order_principal_time']
                        ){
                            $is_execute = true;
                        }
                        break;
                    case ShopOrderModel::getStatus('o_success',1)://完成
                        //立即返款
                        if($setting['order_principal_time']<=0){
                            $is_execute = true;
                        }else if(
                            $order['success_time']
                            && $setting['order_principal_time']>0
                            && hourCalculation($order['success_time'],date('Y-m-d H:i:s'))>=$setting['order_principal_time']
                        ){
                            $is_execute = true;
                        }
                        break;
                }
                if($is_execute){
                    self::orderAmount($order,1);
                }
            }
            /******************************佣金*****************************/
            if(
                $order['is_commission'] == 0
                && $order['commission']>0
                && $setting['order_commission_status'] == ShopOrderModel::getStatus($order['status'],3)
            ){
                $is_execute = false;//是否满足佣金发放条件
                switch ($order['status']){
                    case ShopOrderModel::getStatus('o_delivery',1)://待发货
                        //立即返款
                        if($setting['order_commission_time']<=0){
                            $is_execute = true;
                        }else if(
                            $order['operate_time']
                            && $setting['order_commission_time']>0
                            && hourCalculation($order['operate_time'],date('Y-m-d H:i:s'))>=$setting['order_commission_time']
                        ){
                            $is_execute = true;
                        }
                        break;
                    case ShopOrderModel::getStatus('o_evaluate',1)://待评价
                        //立即返款
                        if($setting['order_commission_time']<=0){
                            $is_execute = true;
                        }else if(
                            $order['ship_time']
                            && $setting['order_commission_time']>0
                            && hourCalculation($order['ship_time'],date('Y-m-d H:i:s'))>=$setting['order_commission_time']
                        ){
                            $is_execute = true;
                        }
                        break;
                    case ShopOrderModel::getStatus('o_success',1)://完成
                        //立即返款
                        if($setting['order_commission_time']<=0){
                            $is_execute = true;
                        }else if(
                            $order['success_time']
                            && $setting['order_commission_time']>0
                            && hourCalculation($order['success_time'],date('Y-m-d H:i:s'))>=$setting['order_commission_time']
                        ){
                            $is_execute = true;
                        }
                        break;
                }
                if($is_execute){
                    self::orderAmount($order,2);
                }
            }
        }else if(
            $order['status'] == ShopOrderModel::getStatus('o_success',1)
            && $order['principal']>$setting['order_max_principal']
        ){
            /******************************本金大于设置本金货返节点，在完成时进行返款*****************************/
            //本金
            if($order['is_principal'] == 0 && $order['setting_refund_id']!=$setting_refund_id){
                self::orderAmount($order,1);
            }
            //佣金
            if($order['is_commission'] == 0){
                self::orderAmount($order,2);
            }
        }
        return true;
    }


    /**
     * 买家本金、佣金定时返款
     * @Author: 易军辉
     * @DateTime:2024-11-08 16:56
     * @return int 返款订单数量
     */
    public static function payMemberAmountTime()
    {
        $count = 0;
        /***************************************查询返款设置***************************************/
        $setting = SystemSettingService::info('order_max_principal,order_principal_status,order_principal_time,order_commission_status,order_commission_time');

        if($setting['order_principal_time']>0 || $setting['order_commission_time']>0){
            /***************************************获取商家返款ID,商家返款，需要商家手动返给买家本金***************************************/
            $setting_refund_id = SettingRefundModel::getRefundType(SettingRefundModel::SJFK,1);
            /***************************************查询时间条件组装***************************************/
            $where = " and (";
            if($setting['order_principal_time']>0){//本金
                $where .=" TIMESTAMPDIFF(HOUR, a.".ShopOrderModel::getStatusTime($setting['order_principal_status']).", NOW()) > ".$setting['order_principal_time'];
            }
            if($setting['order_commission_time']>0){//佣金
                if($where!=" and ("){
                    $where .=" or ";
                }
                $where .=" TIMESTAMPDIFF(HOUR, a.".ShopOrderModel::getStatusTime($setting['order_commission_status']).", NOW()) > ".$setting['order_commission_time'];
            }
            $where .=")";
            /***************************************已接单状态***************************************/
            $status_str = ShopOrderModel::getStatus('o_delivery',1).","
                .ShopOrderModel::getStatus('o_evaluate',1).","
                .ShopOrderModel::getStatus('o_auth',1).","
                .ShopOrderModel::getStatus('o_success',1);
            $sql = <<<SQL
                SELECT * from ya_shop_order as a
                WHERE
                a.is_delete= 0
                and a.member_id is not null
                and a.`status` in ({$status_str})
                and (a.is_principal=0 or a.is_commission=0)
                {$where}
            SQL;
            $list = Db::query($sql);
            $count = count($list);
            foreach ($list as $key=>$order){
                /******************************本金小于等于设置本金货返节点*****************************/
                if($setting['order_max_principal'] == 0 || $order['principal']<=$setting['order_max_principal']){
                    /******************************本金*****************************/
                    if(
                        $order['is_principal'] == 0
                        && $order['principal']>0
                        && $order['actual_amount']>0
                        && $order['setting_refund_id']!=$setting_refund_id
                        && hourCalculation($order[ShopOrderModel::getStatusTime($order['status'])],date('Y-m-d H:i:s'))>=$setting['order_principal_time']
                    ){
                        self::orderAmount($order,1);
                    }
                    /******************************佣金*****************************/
                    if(
                        $order['is_commission'] == 0
                        && $order['commission']>0
                        && hourCalculation($order[ShopOrderModel::getStatusTime($order['status'])],date('Y-m-d H:i:s'))>=$setting['order_commission_time']
                    ){
                        self::orderAmount($order,2);
                    }
                }
            }
        }
        return $count;
    }

    /**
     * 本金或者佣金结算
     * @Author: 易军辉
     * @DateTime:2024-09-14 14:28
     * @param $order 订单信息
     * @param $type 1、本金 2、佣金
     */
    private static function orderAmount($order,$type=1){
        if($type==1){
            /******************************实付金额与订单本金差异处理*****************************/
            if($order['principal']!=$order['actual_amount'] && $order['difference_amount']==0){
                $order['difference_amount'] = self::orderActualAmount($order,false);
            }
            //判断实付金额+差额是否等于订单本金
            $sum_amount = bcadd($order['actual_amount'], $order['difference_amount'],2);
            if($sum_amount!=$order['principal']){
                return false;
            }
            $principal_res = MemberService::income(
                $order['member_id'],
                $order['actual_amount'],
                $order['actual_amount'],
                0,
                null,//订单本金返款
                $order['id'],
                $order['member_account_id'],
                '结算订单：'.$order['id'],
                'YHBT'
            );
            $edit = Db::name('shop_order')->where('id',$order['id'])->update([
                'is_principal'=>1,
                'principal_time'=>date('Y-m-d H:i:s')
            ]);
            //给买家发送消息通知
            MemberMessageService::add([
                'title'=>MemberBillModel::getType('YHBT',2),
                'content'=>'您的订单：'.$order['id'].'，'.$order['actual_amount'].'元补贴已到账',
                'member_id'=>$order['member_id'],
                'data_id'=>$order['id'],
            ]);
        }
        if($type==2){
            $commission_res = MemberService::income(
                $order['member_id'],
                $order['commission'],
                0,
                $order['commission'],
                null,//订单佣金返款
                $order['id'],
                $order['member_account_id'],
                '结算订单：'.$order['id'],
                'PTBT'
            );
            $edit = Db::name('shop_order')->where('id',$order['id'])->update([
                'is_commission'=>1,
                'commission_time'=>date('Y-m-d H:i:s')
            ]);
            //给买家发送消息通知
            MemberMessageService::add([
                'title'=>MemberBillModel::getType('PTBT',2),
                'content'=>'您的订单：'.$order['id'].'，'.$order['commission'].'元补贴已到账',
                'member_id'=>$order['member_id'],
                'data_id'=>$order['id'],
            ]);
            //推广费用结算
            $pay_res = self::payPromotionFee($order);
        }
        return true;
    }

    /**
     * 推广费用结算
     * @Author: 易军辉
     * @DateTime:2024-09-11 16:46
     * @param $order
     */
    public static function payPromotionFee($order)
    {
        $promotion_data = [
            'shop_order_id'=>$order['id'],
            'member_remark'=>"",
            'promotion_remark'=>"",
        ];
        //查询基础佣金
        $basic_price = Db::name('shop_product_price')
            ->where('shop_product_id',$order['shop_product_id'])
            ->whereIn('id',$order['shop_product_price_ids'])
            ->where('type','basic_price')
            ->value('price');
        if(!$basic_price || $basic_price<=0){
            $basic_price = 0;
        }
        /******************************买家分销******************************************************/
        $setting = MemberSettingService::info('is_distribution,distribution_mode');
        if($setting['is_distribution']==1 && $order['member_id']){//开启分销
            //查询上级会员
            $member =  Db::name('member')
                ->where('member_id',$order['member_id'])
                ->field('member_id,pid')
                ->find();
            $pid_members = self::member_pid($member['pid'],0,[],$setting['distribution_mode']);
            foreach ($pid_members as $key=>$val){
                //计算佣金
                $amount = 0;
                if($val['rebate_type'] ==1){
                    //固定返佣
                    $amount = $val['rebate'];
                }else if($val['rebate_type'] ==2){
                    //比例返佣
                    $amount =bcmul($basic_price, bcdiv($val['rebate'], 100,4),2);
                }
                //备注推荐人等级编码
                if($promotion_data['member_remark']!=""){
                    $promotion_data['member_remark'] .=",";
                }
                $promotion_data['member_remark'] .="level".$val['level'].":".$val['code'];
                if($amount<=0){
                    continue;
                }
                //判断店铺平台是否匹配
                $setting_store_platform_ids = explode(',', $val['setting_store_platform_ids']);
                if(!in_array($order['store_platform_id'], $setting_store_platform_ids)){
                    continue;
                }
                switch ($val['level']){
                    case 1:
                        $promotion_data['one_member_id'] = $val['member_id'];
                        $promotion_data['one_amount'] = $amount;
                        break;
                    case 2:
                        $promotion_data['two_member_id'] = $val['member_id'];
                        $promotion_data['two_amount'] = $amount;
                        break;
                    case 3:
                        $promotion_data['three_member_id'] = $val['member_id'];
                        $promotion_data['three_amount'] = $amount;
                        break;
                }
                //转账
                $commission_res = MemberService::income(
                    $val['member_id'],
                    $amount,
                    0,
                    $amount,
                    null,//推广佣金
                    $order['id'],
                    $order['member_account_id'],
                    '结算订单：'.$order['id'],
                    'XJTC'
                );
                //给买家发送消息通知
                MemberMessageService::add([
                    'title'=>'邀请红包通知',
                    'content'=>'您的下级订单：'.$order['id'].'，提成'.$amount.'元已到账',
                    'member_id'=>$val['member_id'],
                    'data_id'=>$order['id'],
                ]);
            }
        }
        /******************************推广员结算******************************************************/
        $promotion_user_id = Db::name('merchant')
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->where('id',$order['merchant_id'])
            ->value('promotion_user_id');
        $promotion_list = self::promotion_pid($promotion_user_id,$level=0,$result = []);
        foreach ($promotion_list as $k=>$v){
            if($v['level']>3){
                break;
            }
            $amount =bcmul($basic_price, bcdiv($v['rebate'], 100,4),2);
            //备注推荐人等级比例
            if($promotion_data['promotion_remark']!=""){
                $promotion_data['promotion_remark'] .=",";
            }
            $promotion_data['promotion_remark'] .="level".$v['level'].":".$v['rebate'];
            if($amount<=0){
                continue;
            }
            switch ($v['level']){
                case 1:
                    $promotion_data['one_promotion_user_id'] = $v['promotion_user_id'];
                    $promotion_data['one_promotion_amount'] = $amount;
                    break;
                case 2:
                    $promotion_data['two_promotion_user_id'] = $v['promotion_user_id'];
                    $promotion_data['two_promotion_amount'] = $amount;
                    break;
                case 3:
                    $promotion_data['three_promotion_user_id'] = $v['promotion_user_id'];
                    $promotion_data['three_promotion_amount'] = $amount;
                    break;
            }
            //转账
            $commission_res = PromotionUserService::income(
                $v['promotion_user_id'],
                $amount,
                '推广佣金',
                $order['id'],
                '商家ID：'.$order['merchant_id'].",订单ID：".$order['id'],
                $order['merchant_id'],
            );
        }
        //保存结算推广费
        $promotion = Db::name('shop_order_promotion')->where('shop_order_id',$order['id'])->find();
        if($promotion){
            return Db::name('shop_order_promotion')->where('shop_order_id',$order['id'])->update($promotion_data);
        }else{
            return Db::name('shop_order_promotion')->insert($promotion_data);
        }
    }

    /**
     * 查询商家推广员
     * @Author: 易军辉
     * @DateTime:2024-09-12 16:11
     * @param $promotion_user_id 推广员id
     * @param $level 层级
     * @param $result 结果
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private static function promotion_pid($promotion_user_id=0,$level=0,$result = [])
    {
        if(!$promotion_user_id || $promotion_user_id<=0){
            return $result;
        }
        $promotion_user = Db::name('promotion_user')
            ->where('promotion_user_id',$promotion_user_id)
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->field('promotion_user_id,pid,level,commission_ratio,p_commission_ratio')
            ->find();
        if(!$promotion_user){
            return $result;
        }
        $rebate = 0;
        if($level==0){
            $rebate = $promotion_user['commission_ratio'];
        }else{
            $rebate =$result[$level-1]['p_commission_ratio'];
        }
        $level +=1;
        $result[] = [
            'promotion_user_id'=>$promotion_user['promotion_user_id'],
            'pid'=>$promotion_user['pid'],
            'level'=>$level,
            'rebate'=>$rebate,
            'p_commission_ratio'=>$promotion_user['p_commission_ratio'],
            'commission_ratio'=>$promotion_user['commission_ratio'],
        ];
        return self::promotion_pid($promotion_user['pid'],$level,$result);
    }
    /**
     * 查询买家上级
     * @Author: 易军辉
     * @DateTime:2024-09-12 10:27
     * @param $member_id 上级买家id
     * @param $level 等级
     * @param $result 查询结果
     * @param $distribution_mode 分销等级
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private static function member_pid($member_id=0,$level=0, $result = [],$distribution_mode = 1)
    {
        // 如果当前级别已经达到分销等级，停止递归
        if ($level >= $distribution_mode) {
            return $result;
        }
        $member =  Db::name('member')->alias('a')
            ->leftJoin('member_distribution','a.member_distribution_id = member_distribution.id')
            ->where('a.is_disable',0)
            ->where('a.is_delete',0)
            ->where('member_distribution.is_disable',0)
            ->where('member_distribution.is_delete',0)
            ->where('a.member_id',$member_id)
            ->field('a.member_id,
                    a.pid,
                    member_distribution.code,
                    member_distribution.rebate_type,
                    member_distribution.rebate_one,
                    member_distribution.rebate_two,
                    member_distribution.rebate_three,
                    member_distribution.setting_store_platform_ids
            ')->find();
        if(!$member){
            return $result;
        }
        $level +=1;
        $rebate = 0;
        switch ($level){
            case 1:
                $rebate = $member['rebate_one'];
                break;
            case 2:
                $rebate = $member['rebate_two'];
                break;
            case 3:
                $rebate = $member['rebate_three'];
                break;
        }
        $result[] = [
            'member_id'=>$member['member_id'],
            'pid'=>$member['pid'],
            'level'=>$level,
            'code'=>$member['code'],
            'rebate_type'=>$member['rebate_type'],
            'rebate'=>$rebate,
            'setting_store_platform_ids'=>$member['setting_store_platform_ids'],
        ];
        return self::member_pid($member['pid'],$level,$result,$distribution_mode);
    }

    /**
     * 自选买号匹配订单
     * @Author: 易军辉
     * @DateTime:2024-06-27 16:21
     * @param $ids
     * @param $param
     * @return array|mixed
     * @throws \think\Exception
     */
    public static function matchingOrder($ids, $param = [])
    {
        $model = new ShopOrderModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $merchantId = mer_id();
        $list = $model->where('id','in',$ids)
                ->where('is_delete',0)
                ->where('is_self_selection',1)
                ->whereNull('member_id')
                ->whereNull('member_account_id')
                ->where('status','in',[
//                    ShopOrderModel::getStatus('o_listing',1),
                    ShopOrderModel::getStatus('o_select',1)
                ])
                ->where(function($query){
                    $query->whereNull('pending_time')->whereOr('pending_time','<=',date('Y-m-d H:i:s'));
                })
                ->when($merchantId>0, function($query) use ($merchantId) {
                    $query->where('merchant_id', $merchantId);
                })->select();
        $member_accounts = Db::name('member_account')
            ->where('id','in',$param['member_account_ids'])
            ->field('id,member_id')
            ->select()
            ->toArray();
        if(count($list)>count($member_accounts)){
            exception("买号数量小于订单数量");
        }
        //操作用户
        $matching_uid = mer_user_id();
        if($matching_uid<=0){
            $matching_uid = user_id();
        }
        // 启动事务
        $model->startTrans();
        try {
            $setting = MemberSettingService::info('order_effective_time');
            if(!isset($setting['order_effective_time']) || $setting['order_effective_time']<=0){
                $setting['order_effective_time'] = 60*60*24;//若没有设置，则默认一天
            }else{
                $setting['order_effective_time'] +=10;//加10秒损耗时间
            }
            foreach ($list as $key=>$val){
//                $val->member_id = $member_accounts[$key]['member_id'];
//                $val->member_account_id = $member_accounts[$key]['id'];
                $val->pending_member_id = $member_accounts[$key]['member_id'];
                $val->pending_member_account_id = $member_accounts[$key]['id'];
                $val->pending_time = date('Y-m-d H:i:s', (time()+$setting['order_effective_time']));
                $val->matching_uid = $matching_uid;
                $val->matching_time = date('Y-m-d H:i:s');
                $val->save();
                //通知用户有待接订单
                CacheRedisService::set('OrderAssignListener_'.$val['pending_member_id'],$val['id'],$setting['order_effective_time']);
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }
        $param['ids'] = $ids;
        ShopOrderCache::del($ids);
        return $param;
    }

    /**
     * 申诉
     * @Author: 易军辉
     * @DateTime:2024-06-28 10:30
     * @param $id 订单ID
     * @param $param 申诉参数
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function appeal($id, $param)
    {
        $model = new ShopOrderModel();
        $merchantId = 0;
        $memberId = 0;
        $create_uid = 0;
        if($param['is_terminal'] ==1){
            $merchantId = mer_id(true);
            $create_uid = mer_user_id(true);
        }else if($param['is_terminal'] ==2){
            $memberId = member_id(true);
            $create_uid = $memberId;
        }

        $info = $model
            ->when($merchantId>0, function($query) use ($merchantId) {
                $query->where('merchant_id', $merchantId);
            })
            ->when($memberId>0, function($query) use ($memberId) {
                $query->where('member_id', $memberId);
            })
            ->find($id);
        if (empty($info)) {
            exception('订单不存在：' . $id);
            return [];
        }
        if((!$info['member_id'] && !$info['member_account_id'])){
            exception("您申诉的订单还未有买家接单");
        }
        if($param['is_terminal'] ==1 && $info['status']<=ShopOrderModel::getStatus('o_operation',1)){
            exception("您申诉的订单状态暂不支持申诉");
        }else if($param['is_terminal'] ==2 && $info['status']<ShopOrderModel::getStatus('o_operation',1)){
            exception("您申诉的订单状态暂不支持申诉");
        }

        $info = $info->toArray();
        //判断是否已有未完结的申诉订单
        $order_appeal = Db::name('shop_order_appeal')
            ->where('shop_order_id',$info['id'])
            ->where('is_disable',0)
            ->where('is_delete',0)
            ->whereNotIn('status',[2,3])
            ->find();
        if($order_appeal){
            exception("订单ID：".$info['id']."，请先完结已有待处理的申诉");
        }

        // 启动事务
        $model->startTrans();
        try {
            //获取图片
            $image_ids = "";
            if(isset($param['image_ids']) && $param['image_ids']){
                foreach ($param['image_ids'] as $key=>$val){
                    if($image_ids!=""){
                        $image_ids .=",";
                    }
                    $image_ids .=$val['file_id'];
                }
            }
            $appeal_data = array(
                'merchant_id'=>$info['merchant_id'],//商家ID
                'shop_order_id'=>$info['id'],//订单ID
                'shop_order_on'=>$info['order_on'],//订单号
                'setting_appeal_type_id'=>$param['setting_appeal_type_id'],//申诉类型ID
                'is_terminal'=>isset($param['is_terminal'])?$param['is_terminal']:1,//终端：1、商家端 2、买家端
                'member_id'=>$info['member_id'],//买家ID
                'member_account_id'=>$info['member_account_id'],//接单账号ID
                'status'=>0,//状态：0、待处理 1、处理中 2、完结 3、驳回
                'is_tip'=>0,//是否提醒：0、未提醒  1、已提醒
                'content'=>isset($param['content'])?$param['content']:'',//申诉内容
                'image_ids'=>$image_ids,//截图id(多个逗号隔开)
                'create_uid'=>$create_uid,//添加用户id
                'create_time'=>date('Y-m-d H:i:s'),//创建时间
            );
            $appeal_id = Db::name('shop_order_appeal')->insertGetId($appeal_data);

            if($appeal_id){
                $appeal_message_data = array(
                    'shop_order_appeal_id'=>$appeal_id,//申诉表ID
                    'is_terminal'=>$appeal_data['is_terminal'],//终端：1、商家端 2、买家端
                    'merchant_id'=>$appeal_data['merchant_id'],//商家ID
                    'member_account_id'=>$appeal_data['member_account_id'],//接单账号ID
                    'member_id'=>$appeal_data['member_id'],//买家ID
                    'content'=>$appeal_data['content'],//内容
                    'image_ids'=>$appeal_data['image_ids'],//截图id(多个逗号隔开)
                    'create_uid'=>$appeal_data['create_uid'],//添加用户id
                    'create_time'=>$appeal_data['create_time'],//创建时间
                );
                $message_res = Db::name('shop_order_appeal_message')->insert($appeal_message_data);
                //订单日志
                $log_data = array(
                    'merchant_id'=>$info['merchant_id'],
                    'shop_order_id'=>$info['id'],
                    'order_status'=>$info['status'],
                    'code'=>'SJFQSS',
                    'title'=>ShopOrderLogModel::getStatus('SJFQSS',2),
                    'create_uid'=>$appeal_data['create_uid'],
                    'create_time'=>date('Y-m-d H:i:s'),
                );
                $log_res = Db::name('shop_order_log')->insert($log_data);

                //修改订单状态
                $stop_remark = $info['stop_remark']?$info['stop_remark'].",":"";
                if($param['is_terminal'] ==1){
                    $stop_remark .="商家发起申诉";
                }else if($param['is_terminal'] ==2){
                    $stop_remark .="买家发起申诉";
                }
                $order_res = Db::name('shop_order')
                    ->where('id',$info['id'])
                    ->update([
                        'status'=>ShopOrderModel::getStatus('o_stop',1),
                        'old_status'=>$info['status'],
                        'stop_remark'=>$stop_remark,
                        'update_uid'=>$appeal_data['create_uid'],
                        'update_time'=>date('Y-m-d H:i:s'),
                    ]);
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }
        return true;
    }

    /**
     * 修改关键词或者二维码
     * @Author: 易军辉
     * @DateTime:2024-07-03 16:55
     * @param $shop_product_enter_id 进店方式id
     * @param $param 修改参数
     */
    public static function editKeyword($shop_product_enter_id, $param)
    {
        $model = new ShopProductEnterModel();
        $info = $model->find($shop_product_enter_id);
        if (empty($info)) {
            exception('进店方式不存在：' . $shop_product_enter_id);
            return [];
        }
        // 启动事务
        $model->startTrans();
        try {
            if($info['enter_type'] == SettingPriceRangeModel::getEnterType('EWM',2)){
                if(!isset($param['enter_qr_image_id']) || !$param['enter_qr_image_id']){
                    exception("请上传二维码");
                }
                $info->qr_image_id = $param['enter_qr_image_id'];
            }else{
                if(!isset($param['keyword']) || !$param['keyword']){
                    exception("请设置".SettingPriceRangeModel::getEnterType($info['enter_type'],1));
                }
                $info->keyword = $param['keyword'];
            }
            $info->save();
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }
        if (isset($errmsg)) {
            exception($errmsg);
        }
        return true;
    }

    /**
     * 添加发布评论/追加评论
     * @Author: 易军辉
     * @DateTime:2024-07-04 11:24
     * @param $id 订单ID
     * @param $param 参数
     */
    public static function addComment($id, $param)
    {
        $model = new ShopOrderModel();
        $merchantId = mer_id();
        $info = $model->when($merchantId>0, function($query) use ($merchantId) {
            $query->where('merchant_id', $merchantId);
        })->find($id);
        if (empty($info)) {
            exception('订单不存在：' . $id);
            return [];
        }
        //发布评论，订单状态不能大于评价待审核
        if($param['comment_status'] ==2 && $info['status']>=ShopOrderModel::getStatus('o_auth',1)){
            exception("该订单状态不支持发布评论");
        }
        //浏览任务不发布
        if($info['shop_product_type_code'] == ShopProductTypeModel::LLRW){
            exception("浏览任务订单无需评价");
        }
        // 启动事务
        $model->startTrans();
        try {
            $comment_status_title = $param['comment_status']==2?'发布评论':'追加评论';
            //好评图片
            $comment_image_ids =[];
            if(isset($param['comment_image_id']) && count($param['comment_image_id'])>0){
                foreach ($param['comment_image_id'] as $k=>$v){
                    array_push($comment_image_ids,$v['file_id']);
                }
            }
            //查询区间价格
            $comment_model = Db::name('setting_price_range')
                ->where('is_disable',0)
                ->where('is_delete',0)
                ->where('id',$param['setting_price_range_id'])
                ->find();
            if(!$comment_model){
                exception("未查询到评论方式");
            }
            //查询是否已存在追评
            $comment = Db::name('shop_order_comment')
                ->where('shop_order_id',$info['id'])
                ->where('comment_status',$param['comment_status'])
                ->where('is_delete',0)
                ->field('id')
                ->find();
            if($comment){
                exception("订单ID：".$info['id']."，已存在".$comment_status_title);
            }
            $data = array(
                'merchant_id'=>$info['merchant_id'],//商家ID
                'shop_order_id'=>$info['id'],//订单ID
                'store_platform_id'=>$info['store_platform_id'],//店铺平台ID
                'shop_product_type_id'=>$info['shop_product_type_id'],//活动类型【平台补贴、垫付任务、浏览任务】
                'setting_price_range_id'=>$comment_model['id'],//价格区间表ID
                'member_id'=>$info['member_id'],//接单人id
                'member_account_id'=>$info['member_account_id'],//接单人账号ID
                'comment_status'=>$param['comment_status'],//评论类型：2、发布评论  3、追加评论
                'comment_type'=>$param['comment_type'],//评论方式：2、文字评价、3、图文评价、4、视频评价
                'comment_type_code'=>$param['comment_type_code'],//评论方式编码
                'content'=>$param['content'],//评论内容
                'comment_image_id'=>implode(',',$comment_image_ids),//多个图片逗号隔开
                'comment_vido_id'=>isset($param['comment_vido_id'])?$param['comment_vido_id']:null,//视频ID
                'push_time'=>isset($param['push_time'])?$param['push_time']:0,//推送时间
                'is_anonymous'=>isset($param['is_anonymous'])?$param['is_anonymous']:null,//是否匿名评价：1、是 0、否
                'is_close_comments'=>isset($param['is_close_comments'])?$param['is_close_comments']:null,//是否关闭评论：1、是 0、否
                'commission'=>$comment_model['user_consumption'],//买手所得佣金
                'mer_commission'=>$comment_model['merchant_fees'],//商家支付的佣金
                'status'=>1,//状态：0、待发布评价 1、待提交 2、待审核  3、审核被拒 4、已完成
                'create_uid'=>mer_user_id(),//添加用户id
                'create_time'=>date('Y-m-d H:i:s'),//创建时间
            );
            $shop_order_comment_id = Db::name('shop_order_comment')->insertGetId($data);

            //佣金支付
            $consumption_res = MerchantService::consumption($data['mer_commission'], 0, $data['mer_commission'], $comment_status_title, $shop_order_comment_id, null,'订单ID：'.$info['id']);
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }
        if (isset($errmsg)) {
            exception($errmsg);
        }
        return true;
    }

    /**
     * 查询评价管理参数
     * @Author: 易军辉
     * @DateTime:2024-07-04 19:42
     */
    public static function  getCommentParams()
    {
        $order_comment_status = ShopOrderCommentModel::STATUS;
        return compact('order_comment_status');
    }

    /**
     * 好评审核
     * @Author: 易军辉
     * @DateTime:2024-07-05 15:39
     * @param $ids 订单ID
     * @param $param 审核参数
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function commentAuth($ids, $param = [])
    {
        $model = new ShopOrderCommentModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $list = $model
            ->where('shop_order_id', 'in', $ids)
            ->where('is_delete',0)
            ->where('merchant_id',mer_id())
            ->where('comment_status',$param['comment_status'])
            ->where('status',$model::getStatus('c_auth',1))
            ->select();
        if (count($list)<=0) {
            exception('未查询到符合审核条件的订单');
        }
        // 启动事务
        $model->startTrans();
        try {
            foreach ($list as $k=>$v){
                if(!$v['member_id']){
                    exception($v['shop_order_id'].'该订单未查询到买家');
                }
                $v->auth_time=datetime();
                $v->auth_uid=mer_user_id();
                switch (intval($param['auth_status'])){
                    case 1://审核通过
                        $v->status=$model::getStatus('c_success',1);
                        /********************判断是否在完成时进行返款*********************************/
                        $commission_res = MemberService::income(
                            $v['member_id'],
                            $v['commission'],
                            0,
                            $v['commission'],
                            null,//评价佣金返款
                            $v['id'],
                            $v['member_account_id'],
                            '结算订单：'.$v['shop_order_id'],
                            'PTBT'
                        );
                        break;
                    case 2://审核未通过
                        $v->status=$model::getStatus('c_auth_error',1);
                        $v->auth_remark=$param['auth_msg'];
                        break;
                }
                $v->save();
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }
        return $param;
    }

    /**
     * 撤销评论
     * @Author: 易军辉
     * @DateTime:2024-07-05 18:07
     * @param $ids
     * @param $param
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function revokeComment($ids, $param = [])
    {
        $model = new ShopOrderCommentModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $list = $model
            ->where('shop_order_id', 'in', $ids)
            ->where('is_delete',0)
            ->where('merchant_id',mer_id())
            ->where('comment_status',$param['comment_status'])
            ->where('status',$model::getStatus('c_submit',1))
            ->select();
        if (count($list)<=0) {
            exception('未查询到符合撤销条件的订单');
        }
        // 启动事务
        $model->startTrans();
        try {
            foreach ($list as $k=>$v){
                // 获取当前时间
                $currentDate = new DateTime();
                // 计算时间差
                $createTime = DateTime::createFromFormat('Y-m-d H:i:s', $v['create_time']);
                $interval = $currentDate->diff($createTime);
                if ($interval->days < 3) {
                    exception('订单ID：'.$v['shop_order_id']."，时间未超过3天，不允许撤销");
                }
                //退款
                $consumption_res = MerchantService::refund(
                    $v['merchant_id'],
                    $v['mer_commission'],
                    0,
                    $v['mer_commission'],
                    '评论撤销退款',
                    $v['shop_order_id'],
                    null,
                    "订单ID：".$v['shop_order_id']
                );
                $v->is_delete = 1;
                $v->delete_time = date('Y-m-d H:i:s');
                $v->save();
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }
        return $param;
    }

    /**
     * 查询商家返款参数
     * @Author: 易军辉
     * @DateTime:2024-07-04 19:42
     */
    public static function  getMerRefundParams()
    {
        $mer_refund_status = ShopOrderModel::REFUND_STATUS;
        return compact('mer_refund_status');
    }

    /**
     * 商家返款审核
     * @Author: 易军辉
     * @DateTime:2024-07-16 14:35
     * @param $ids 订单id
     * @param $param 审核参数
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function merRefundAuth($ids, $param = [])
    {
        $model = new ShopOrderModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        //获取商家返款ID,商家返款，需要商家手动返给买家本金
        $setting_refund_id = SettingRefundModel::getRefundType(SettingRefundModel::SJFK,1);
        $merchantId = mer_id();
        $list = $model
            ->where('id', 'in', $ids)
            ->where('is_delete',0)
            ->where('setting_refund_id',$setting_refund_id)
            ->when($merchantId>0, function($query) use ($merchantId) {
                $query->where('merchant_id', $merchantId);
            })
            ->where('status','in',[
//                ShopOrderModel::getStatus('o_delivery',1),
                ShopOrderModel::getStatus('o_evaluate',1),
                ShopOrderModel::getStatus('o_auth',1),
                ShopOrderModel::getStatus('o_success',1),
            ])
            ->whereNotIn('mer_refund_status',ShopOrderModel::getRefundStatus('o_success',1))
            ->select();
        if (count($list)<=0) {
            exception('未查询到符合返款条件的订单');
        }
        // 启动事务
        $model->startTrans();
        try {
            foreach ($list as $k=>$v){
                $v->mer_refund_time=datetime();
                $v->mer_refund_uid=$merchantId;
                $v->mer_refund_status=intval($param['mer_refund_status']);
                //返款失败需要保存失败原因
                if($v->mer_refund_status == ShopOrderModel::getRefundStatus('o_error',1)){
                    $v->mer_refund_msg=$param['mer_refund_msg'];
                }else if($v->mer_refund_status == ShopOrderModel::getRefundStatus('o_success',1)){
                    //判断实付金额+差额是否等于订单本金
                    $actual_amount = $v['principal'];
                    $sum_amount = bcadd($v['actual_amount'], $v['difference_amount'],2);
                    if($v['principal']!=$v['actual_amount'] && $sum_amount==$v['principal']){
                        $actual_amount = $v['actual_amount'];
                    }

                    if($sum_amount!=$v['principal']){
                        return false;
                    }
                    //返款成功
                    $refund_type_title = "支付宝";
                    switch ($param['mer_refund_type']){
                        case 1:
                            $refund_type_title = "支付宝";
                            break;
                        case 2:
                            $refund_type_title = "微信";
                            break;
                        case 3:
                            $refund_type_title = "银行卡";
                            break;
                    }
                    $principal_res = MemberService::income(
                        $v['member_id'],
                        $actual_amount,
                        $actual_amount,
                        0,
                        null,//订单本金返款
                        $v['id'],
                        $v['member_account_id'],
                        '结算订单：'.$v['id']."，返款方式：".$refund_type_title,
                        'SJFK'
                    );
                    $v->is_principal = 1;
                    $v->principal_time = date('Y-m-d H:i:s');
                    $v->mer_refund_type = $param['mer_refund_type'];
                    //给买家发送消息通知
                    MemberMessageService::add([
                        'title'=>MemberBillModel::getType('SJFK',2),
                        'content'=>'您的订单：'.$v['id'].'，'.$actual_amount.'元商家返款已到账',
                        'member_id'=>$v['member_id'],
                        'data_id'=>$v['id'],
                    ]);
                }
                $v->save();
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }
        return $param;
    }

    /**
     * 订单单表查询
     * @Author: 易军辉
     * @DateTime:2024-08-22 17:50
     * @param $where 条件
     * @param $page 页数
     * @param $limit 数量
     * @param $order 排序
     * @param $field 字段
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getList($where = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        $model = new ShopOrderModel();
        $pk = $model->getPk();
        if (empty($field)) {
            $field = 'id,merchant_id';
        }
        if (empty($order)) {
            $order = ['sort'=>'asc',$pk => 'desc'];
        }
        if ($page == 0 || $limit == 0) {
            return $model->field($field)->where($where)->order($order)->select()->toArray();
        }
        $count = $model->where($where)->count();
        $pages = ceil($count / $limit);
        $list = $model->field($field)->where($where)->page($page)->limit($limit)->order($order)->select()->toArray();
        return compact('count', 'pages', 'page', 'limit', 'list');
    }

    /**
     * 特制修改方法
     * @Author: 易军辉
     * @DateTime:2024-08-22 19:06
     * @param $where 条件
     * @param $param 修改内容
     * @return array|mixed
     * @throws \think\Exception
     */
    public static function customEdit($where, $param = [])
    {
        if(count($where)<=0){
            return false;
        }
        $model = new ShopOrderModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $user_id = user_id();
        if($user_id>0){
            $param['update_uid']  = $user_id;
        }
        $param['update_time'] = datetime();
        $ids=[];
        // 启动事务
        $model->startTrans();
        try {
            foreach ($where as $key=>$val){
                if($val[0] == $pk){
                    if(is_array($val[2])){
                        $ids = $val[2];
                    }else{
                        array_push($ids,$val[2]);
                    }
                }
            }
            $res = $model->where($where)->update($param);
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }
        if (isset($errmsg)) {
            exception($errmsg);
        }
        $param['ids'] = $ids;
        ShopOrderCache::del($ids);
        return $param;
    }

    /**
     * 查询需要派单的订单
     * @Author: 易军辉
     * @DateTime:2024-08-23 14:34
     * @return mixed
     */
    public static function getOrderAssigns($cache_ids)
    {
        $o_select = ShopOrderModel::getStatus('o_select',1);//待自选
        $o_taking = ShopOrderModel::getStatus('o_taking',1);//待接单
        $ptbt = ShopProductTypeModel::PTBT;
        $time = date('Y-m-d H:i:s');
        $where = "";
        if($cache_ids && count($cache_ids)>0){
            $where =" and id not in(".implode(',',$cache_ids).")";
        }
        $sql = <<<SQL
            SELECT * from ya_shop_order 
            where 
            (status = {$o_taking} 
            or (status = {$o_select} and pending_member_id is not null and pending_member_account_id is not null))
            and shop_product_type_code <> '{$ptbt}'
            and (pending_time is null or pending_time < '{$time}')
            {$where}
            order by status asc
        SQL;
//        echo $sql;exit();
        $list = Db::query($sql);
        return $list;
    }

    /**
     * 查询待接订单
     * @Author: 易军辉
     * @DateTime:2024-08-29 12:14
     * @param $member_id
     * @return mixed
     */
    public static function getOrderByMember($member_id=0)
    {
        if(!$member_id){
            return [];
        }
        $o_select = ShopOrderModel::getStatus('o_select',1);//待自选
        $o_taking = ShopOrderModel::getStatus('o_taking',1);//待接单
        $ptbt = ShopProductTypeModel::PTBT;
        $sql = <<<SQL
            SELECT 
            platform.title as platform_title,
            platform.image_id as platform_image_id,
            account.accname,
            account.consignee,
            account.phone,
            account.region_id as ac_region_id,
            account.address,
            a.id,
            a.pending_time,
            TIMESTAMPDIFF(SECOND,NOW(), a.pending_time) AS time_diff_in_seconds,
            a.principal,
            a.commission,
            product.money as product_money,
            goods.image_id as goods_image_id,
            goods.goods_title,
            enter.keyword as enter_keyword,
            enter.enter_type,
            enter.qr_image_id as enter_qr_image_id
            from ya_shop_order as a
            -- 关联接单账号表
            LEFT JOIN ya_member_account as account ON a.pending_member_account_id = account.id
            -- 关联店铺平台表
            LEFT JOIN ya_setting_store_platform as platform ON account.store_platform_id=platform.id
            -- 关联商品表，取第一条商品
            LEFT JOIN (
                    SELECT goods.*
                    FROM ya_shop_product_goods as goods
                    WHERE (goods.shop_product_id,goods.id) IN (
                            SELECT shop_product_id, MIN(id) 
                            FROM ya_shop_product_goods 
                            GROUP BY shop_product_id
                    )
            ) AS goods ON a.shop_product_id = goods.shop_product_id
            -- 关联进店方式
            LEFT JOIN ya_shop_product_enter as enter ON enter.id=a.shop_product_enter_id
            -- 关联商品表
            LEFT JOIN ya_shop_product as product ON product.id=a.shop_product_id
            where 
            a.status in ({$o_taking},{$o_select})
            and a.pending_member_id = {$member_id}
            and a.pending_time > NOW()
            and a.shop_product_type_code <> '{$ptbt}'
            and a.is_delete=0
        SQL;
//        echo $sql;exit();
        $list = Db::query($sql);
        foreach ($list as $key=>$item){
            //店铺平台图片
            if($item['platform_image_id']){
                $file = FileService::info($item['platform_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['platform_image_url'] =$file['file_url'];
                }
            }
            //商品缩略图
            if($item['goods_image_id']){
                $file = MerchantFileService::info($item['goods_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['goods_image_url'] =$file['file_url'];
                }
            }

            //收货地址
            $item['ac_region_str'] = "";
            if($item['ac_region_id']){
                $region = RegionService::info($item['ac_region_id']);
                if(isset($region['region_fullname'])){
                    $list[$key]['ac_region_str']  =$region['region_fullname'];
                }
            }
            //进店方式
            if(isset($item['enter_type'])){
                $list[$key]['enter_type_str'] = SettingPriceRangeModel::getEnterType($item['enter_type'],1);
            }
            //二维码
            $list[$key]['enter_qr_image_url'] ="";
            if(isset($item['enter_qr_image_id']) && $item['enter_qr_image_id']){
                $file = MerchantFileService::info($item['enter_qr_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['enter_qr_image_url'] =$file['file_url'];
                }
            }
            //价格区间
            $list[$key]['principal_str'] = self::getPriceRange($item['principal']);
            unset($list[$key]['principal']);
        }
        return $list;
    }

    /**
     * 获取价格区间
     * @Author: 易军辉
     * @DateTime:2024-08-29 16:00
     * @param $amount
     * @return float[]|int[]
     */
    private static function getPriceRange($amount) {
        // 找到最接近的下限和上限
        $lowerBound = floor($amount / 50) * 50;
        $upperBound = $lowerBound + 50;

        return number_format($lowerBound, 2)."-".number_format($upperBound, 2);
    }

    /**
     * 查询订单状态
     * @Author: 易军辉
     * @DateTime:2024-08-29 20:57
     * @param $type 0、全部 1、买家端订单列表
     * @return array
     */
    public static function getOrderStatus($type=0){
        $order_status = ShopOrderModel::STATUS;
        if($type == 1){
            foreach ($order_status as $key=>$val){
                if($val['value']<ShopOrderModel::getStatus('o_operation',1)){
                    unset($order_status[$key]);
                }
            }
            $order_status = array_merge($order_status,[
                ['value' => 11, 'label' => '待追评','code' => 'o_dzp'],
                ['value' => 12, 'label' => '追评待审核','code' => 'o_zpdsh'],
                ['value' => 13, 'label' => '追评完成','code' => 'o_zpwc'],
                ['value' => 14, 'label' => '追评被拒','code' => 'o_zpbj'],
            ]);
//            array_unshift($order_status, ['value' => -1, 'label' => '全部','code' => 'all']);
        }
        return compact('order_status');
    }

    /**
     * 订单提交
     * @Author: 易军辉
     * @DateTime:2024-09-09 17:47
     * @param $info
     */
    public static function submitOrder($info)
    {
        if(isset($info['id'])){
            Db::startTrans();
            try {
                $where = [
                    ['id','=',$info['id']],
                    ['is_delete','=',0],
                    ['member_id','=',member_id(true)]
                ];
                $order_model = self::info($where);
                if (empty($order_model)) {
                    exception('订单不存在');
                    return [];
                }
                switch ($order_model['status']){
                    case ShopOrderModel::getStatus('o_operation',1)://待操作
                        //处理实付金额
                        if($order_model['shop_product_type_code'] == 'PTBT'){
                            if($order_model['order_price'] != $info['advance_amount']){
                                $info['actual_amount'] = bcsub($info['advance_amount'], $order_model['activity_price'],2);
                            }else{
                                $info['actual_amount'] =$order_model['principal'];
                            }
                        }
                        if(self::orderValidation($info,$order_model)){
                            $answer_data = $info['order_answer'];
                            $answer_data['shop_order_id'] =  $order_model['id'];
                            $answer_data['merchant_id'] =  $order_model['merchant_id'];
                            $answer_data['merchant_shop_id'] =  $order_model['merchant_shop_id'];
                            $answer_data['member_id'] =  $order_model['member_id'];
                            $answer_data['member_account_id'] =  $order_model['member_account_id'];
                            if(isset($answer_data['other'])){
                                $answer_data['other'] = json_encode($answer_data['other']);
                            }
                            $is_answer_id = Db::name('shop_order_answer')->where('shop_order_id',$order_model['id'])->where('is_delete',0)->value('id');
                            if($is_answer_id && $is_answer_id>0){
                                $answer_res = Db::name('shop_order_answer')->where('id',$is_answer_id)->where('shop_order_id',$order_model['id'])->update($answer_data);
                            }else{
                                $answer_res = Db::name('shop_order_answer')->insert($answer_data);
                            }
                            if($answer_res){
                                $operate_time = datetime();
                                //平台补贴商品 垫付金额处理
                                $advance_amount = 0;
                                if($order_model['shop_product_type_code'] == 'PTBT'){
                                    $advance_amount = isset($info['advance_amount'])?$info['advance_amount']:$order_model['order_price'];
                                }
                                $edit = Db::name('shop_order')->where('id',$order_model['id'])->update([
                                    'actual_amount'=>$info['actual_amount'],
                                    'status'=>ShopOrderModel::getStatus('o_delivery',1),
                                    'old_status'=>$order_model['status'],
                                    'answer'=>isset($info['order_answer']['c_subject'])?$info['order_answer']['c_subject']:'',
                                    'order_on'=>$info['order_on'],
                                    'screenshot_image_id'=>isset($info['order_answer']['pay_image_id'])?$info['order_answer']['pay_image_id']:null,
                                    'advance_amount'=>$advance_amount,
                                    'update_time'=>$operate_time,
                                    'operate_time'=>$operate_time,
                                ]);
                                /********************判断是否在待发货时进行返款*********************************/
                                $order_model['actual_amount'] = $info['actual_amount'];
                                $order_model['status'] = ShopOrderModel::getStatus('o_delivery',1);
                                $order_model['operate_time'] =$operate_time;
                                //查询返款设置
                                $setting = SystemSettingService::info('order_max_principal,order_principal_status,order_principal_time,order_commission_status,order_commission_time');
                                self::payMemberAmount($order_model,$setting);
                                //订单日志
                                $log_res = ShopOrderLogService::addByCode('WCDDTJ',[
                                    'merchant_id'=>$order_model['merchant_id'],
                                    'shop_order_id'=>$order_model['id'],
                                    'order_status'=>ShopOrderModel::getStatus('o_delivery',1),
                                    'create_uid'=>$order_model['member_id'],
                                ]);
                            }
                        }
                        break;
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                $errmsg = $e->getMessage();
                // 回滚事务
                Db::rollback();
            }
            if (isset($errmsg)) {
                exception($errmsg);
            }
            return true;
        }else{
            exception('订单不存在');
        }
        return [];
    }

    /**
     * 订单效验
     * @Author: 易军辉
     * @DateTime:2024-09-09 18:01
     * @param $info
     */
    private static function orderValidation($info,$order)
    {
        //计算订单本金与实付金额价差
        $setting = SystemSettingService::info('order_actual_amount_differ');
        $differ = abs($info['principal'] - $info['actual_amount']);
        if($differ>$setting['order_actual_amount_differ']){
            if($order['shop_product_type_code'] == 'PTBT'){
                exception('实付金额与垫付金额差额大于'.$setting['order_actual_amount_differ'].",请联系客服");
            }else{
                exception('实付金额与订单本金差额大于'.$setting['order_actual_amount_differ'].",请联系客服");
            }
        }
        if($order['shop_product_type_code'] != 'PTBT') {
            //搜索关键词
            if ($info['enter_type'] == SettingPriceRangeModel::getEnterType('GJC', 2) && !isset($info['order_answer']['keyword'])) {
                exception('请输入关键词链接');
            }
            //货比三家
            if ($info['enter_type'] == SettingPriceRangeModel::getEnterType('GJC', 2) && isset($info['price_condition_code']['hbsjj'])) {
                if (!isset($info['order_answer']['goods_compare1']) || !isset($info['order_answer']['goods_compare2']) || !isset($info['order_answer']['goods_compare3'])) {
                    exception('请完善货比商品链接');
                }
            }
            //主商品浏览时间
            if (isset($info['price_condition_code']['Browsing_time'])) {
                if (!isset($info['order_answer']['goods_url0'])) {
                    exception('请完善主商品链接');
                }
            }
            //店铺名称
            if(!isset($info['order_answer']['shop_title'])){
                exception('请完善店铺名称');
            }else if($info['order_answer']['shop_title'] != $order['shop_title']){
                exception('店铺名称错误');
            }
            //宝贝详情问答
            if(isset($info['c_subject']) && $info['order_answer']['c_subject']!=$order['c_subject']){
                exception('目标商品详情中答案错误');
            }
            //浏览店内副宝贝
            if(isset($info['price_condition_code']['Browsing_Baby'])){
                if(!isset($info['order_answer']['goods_browse1']) || !isset($info['order_answer']['goods_browse2'])){
                    exception('请完善浏览店内附宝贝链接');
                }
            }
        }

        //直播互动留言
        if(isset($info['price_condition_code']['Live_interaction']) && !isset($info['order_answer']['live_room_url'])){
            exception('请完善直播间分享链接');
        }
        //附商品链接
        if(count($info['goods_list'])>1){
            foreach ($info['goods_list'] as $k=>$v){
                if($k>0 && !isset($info['order_answer']['goods_url'.$k])){
                    exception('请完善附商品链接'.$k);
                }
            }
        }
        //勾选确认、与图片上传
        foreach ($info['price_condition_list'] as $key=>$val){
            if($val['radio_type'] == 2 || $val['radio_type'] == 4){
                if(!isset($info['order_answer']['other']['price_range_'.$val['setting_price_range_id'].'_checked'])){
                    $describe = $val['user_describe']?$val['user_describe']:$val['mer_describe'];
                    exception($describe.",请勾选确认");
                }
            }
            if($val['radio_type'] == 1){
                if(!isset($info['order_answer']['other']['price_range_'.$val['setting_price_range_id'].'_image_id'])){
                    $describe = $val['user_describe']?$val['user_describe']:$val['mer_describe'];
                    exception("请上传".$describe."截图");
                }
            }
        }
        //付款截图验证
        if($order['shop_product_type_code']!='LLRW'){
            if(!isset($info['order_answer']['pay_image_id'])){
                exception("请上传付款截图");
            }
            if(!isset($info['order_on'])){
                exception("请输入平台下单的订单号");
            }
            if($info['actual_amount']<=0){
                exception("请输入实付金额");
            }
        }
        return true;
    }

    /**
     * 接单后取消订单
     * @Author: 易军辉
     * @DateTime:2024-09-10 10:50
     */
    public static function cancelOrderByOperation($id, $param = [],$remark="")
    {
        $model = new ShopOrderModel();
        $info = $model->where('id',$id)->where('member_id',$param['member_id'])->find();
        if (empty($info)) {
            exception("订单不存在");
        }
        if($info['status']!=ShopOrderModel::getStatus('o_operation',1)){
            exception(ShopOrderModel::getStatus($info['status'],2)."状态下不允许取消");
        }
        $setting = SystemSettingService::info('order_cancel_return');
        $where = [
            ['id','=',$info['id']],
            ['is_delete','=',0],
            ['member_id','=',$param['member_id']],
            ['status','=',ShopOrderModel::getStatus('o_operation',1)],
        ];
        //查询同商品下是否有已撤销订单
        $count = Db::name('shop_order')
            ->where('shop_product_id',$info['shop_product_id'])
            ->where('is_delete',0)
            ->where('status',ShopOrderModel::getStatus('o_revoke',1))
            ->count();
        // 启动事务
        $model->startTrans();
        try {
            //订单需要回池
            if($info['cancel_num']<$setting['order_cancel_return'] && $count<=0){
                $edit_data = [
                    'member_id'=>null,
                    'member_account_id'=>null,
                    'pending_member_id'=>null,
                    'pending_member_account_id'=>null,
                    'order_on'=>null,
                    'status'=>$info['old_status']==ShopOrderModel::getStatus('o_select',1)?$info['old_status']:ShopOrderModel::getStatus('o_taking',1),
                    'old_status'=>$info['status'],
                    'actual_amount'=>0,
                    'cancel_num'=>$info['cancel_num']+1
                ];
                if(self::customEdit($where,$edit_data)){
                    //订单日志
                    $log_res = ShopOrderLogService::addByCode('DDHC',[
                        'merchant_id'=>$info['merchant_id'],
                        'shop_order_id'=>$info['id'],
                        'order_status'=>$edit_data['status'],
                        'create_uid'=>$info['member_id'],
                        'remark'=>$remark?$remark:'取消买家ID：'.$info['member_id']
                    ]);
                    //删除买家提交记录
                    $answer_del = Db::name('shop_order_answer')->where('shop_order_id',$info['id'])->update([
                        'is_delete'=>1,
                        'delete_time'=>datetime()
                    ]);
                }
            }else{
                //撤销订单
                $edit_data = [
                    'status'=>ShopOrderModel::getStatus('o_revoke',1),
                    'old_status'=>$info['status'],
                ];
                if(self::customEdit($where,$edit_data)){
                    //退款
                    $consumption_res = MerchantService::refund(
                        $info['merchant_id'],
                        bcadd($info['principal'], $info['mer_commission'],2),
                        $info['principal'],
                        $info['mer_commission'],
                        '买家取消订单退款',
                        $info['id'],
                        $info['merchant_shop_id'],
                        "订单ID：".$info['id']
                    );
                    //订单日志
                    $log_res = ShopOrderLogService::addByCode('YCX',[
                        'merchant_id'=>$info['merchant_id'],
                        'shop_order_id'=>$info['id'],
                        'order_status'=>$edit_data['status'],
                        'create_uid'=>$info['member_id'],
                        'remark'=>'取消买家ID：'.$info['member_id']
                    ]);
                }
            }
            /********************处理商品状态*********************************/
            ShopProductService::changeStatus($info['shop_product_id']);
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }
        if (isset($errmsg)) {
            exception($errmsg);
        }
        return $param;
    }

    /**
     * 店铺或宝贝详情验证
     * @Author: 易军辉
     * @DateTime:2024-09-10 15:10
     * @param $id
     * @param $param
     */
    public static function answerVerify($id, $param = [])
    {
        $where = [
            ['id','=',$id],
            ['is_delete','=',0],
            ['member_id','=',$param['member_id']]
        ];
        $info = self::info($where);
        if (empty($info)) {
            exception('订单不存在');
        }
        switch ($param['type']){
            case 1://店铺名称验证
                if($info['shop_title'] != $param['answer']){
                    exception('店铺名称错误');
                }else{
                    return true;
                }
                break;
            case 2://宝贝详情验证
                if($info['c_subject'] != $param['answer']){
                    exception('商品详情答案错误');
                }else{
                    return true;
                }
                break;
        }
        return false;
    }

    /**
     * 订单截图提交
     * @Author: 易军辉
     * @DateTime:2024-09-13 10:18
     * @param $id 订单id
     * @param $param 截图信息
     * @return array|mixed
     * @throws \think\Exception
     */
    public static function submitScreenshot($id, $param = [])
    {
        $model = new ShopOrderModel();
        $info = $model->find($id);
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);

        if (empty($info)) {
            exception('订单不存在：' . $id);
            return [];
        }
        if($info['status'] != ShopOrderModel::getStatus('o_evaluate',1)){
            exception(ShopOrderModel::getStatus($info['status'],2).'状态无需提交截图');
        }
        //判断是否为发布评论
        if(isset($param['evaluate_image_id'])){
            $order_comment_id = Db::name('shop_order_comment')
                ->where('is_delete',0)
                ->where('shop_order_id',$info['id'])
                ->where('status',1)
                ->where('comment_status',2)
                ->order(['create_time'=>'asc'])
                ->value('id');
            if($order_comment_id){
                $comment_res = Db::name('shop_order_comment')
                    ->where('id',$order_comment_id)
                    ->update([
                        'status'=>2,
                        'evaluate_image_id'=>$param['evaluate_image_id'],
                        'submit_time'=>datetime(),
                        'member_id'=>$info['member_id'],
                        'member_account_id'=>$info['member_account_id'],
                    ]);
            }
        }
        $param['update_time'] = datetime();
        $param['evaluate_time'] = datetime();//买家评价提交时间
        $param['status'] =ShopOrderModel::getStatus('o_auth',1);
        $param['old_status'] =$info['status'];
        $res = $model->where($pk, $info['id'])->update($param);
        if (empty($res)) {
            exception();
        }
        //订单日志
        $log_res = ShopOrderLogService::addByCode('PJTJ',[
            'merchant_id'=>$info['merchant_id'],
            'shop_order_id'=>$info['id'],
            'order_status'=>$param['status'],
            'create_uid'=>$info['member_id'],
        ]);
        return $param;
    }
    /**
     * 指定买号
     * @Author: 易军辉
     * @DateTime:2024-06-25 09:31
     * @param $ids
     * @param $param
     */
    public static function is_appoint($ids, $param = [])
    {
        //查询接单账号
        $member_account_model = Db::name('member_account')
            ->alias('a')
            ->leftJoin('member','a.member_id=member.member_id')
            ->where('a.is_disable',0)
            ->where('a.is_delete',0)
            ->where('member.is_disable',0)
            ->where('member.is_delete',0)
            ->where('a.id',$param['member_account_id'])
            ->field('a.id,a.member_id,a.store_platform_id')
            ->find();
        if(!$member_account_model){
            exception('接单账号不存在或已被禁用');
        }
        //淘宝与天猫平台ID特殊处理
        /***************************查询淘宝平台id***********************************************/
        $taobao_ids = SettingStorePlatformModel::getTaobaoIds();
        if(!$taobao_ids){
            $taobao_ids = [0];
        }
        /***************************平台匹配***********************************************/
        $store_platform_ids = [$member_account_model['store_platform_id']];
        if(in_array($member_account_model['store_platform_id'],$taobao_ids)){
            $store_platform_ids =$taobao_ids;
        }
        $model = new ShopOrderModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $list = $model
            ->where($pk, 'in', $ids)
            ->where('is_delete',0)
            ->whereNull('member_id')
            ->whereNull('member_account_id')
            ->whereIn('store_platform_id',$store_platform_ids)
            ->whereIn('status',[
                $model::getStatus('o_listing',1),
                $model::getStatus('o_select',1),
                $model::getStatus('o_taking',1),
            ])
            ->field('id,status,old_status,merchant_id')
            ->select();
        if (count($list)<=0) {
            exception('未查询到符合条件的订单，请检查订单状态、订单所属店铺平台是否与接单账号所属平台一致');
        }
        $order_ids = array_column($list->toArray(),'id');

        // 启动事务
        $model->startTrans();
        try {
            $o_operation =ShopOrderModel::getStatus('o_operation',1);
            $create_uid = user_id();
            foreach ($list as $key=>$val){
                $edit_res = $model->where('id',$val['id'])->update([
                    'pending_member_id'=>null,
                    'pending_member_account_id'=>null,
                    'pending_time'=>null,
                    'meet_time'=>date('Y-m-d H:i:s'),
                    'status'=>$o_operation,
                    'old_status'=>$val['status'],
                    'member_id'=>$member_account_model['member_id'],
                    'member_account_id'=>$member_account_model['id'],
                ]);
                if($edit_res){
                    //订单日志
                    $log_res = ShopOrderLogService::addByCode('MJJD',[
                        'merchant_id'=>$val['merchant_id'],
                        'shop_order_id'=>$val['id'],
                        'order_status'=>$o_operation,
                        'create_uid'=>$create_uid,
                    ]);
                }
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }
        $param['ids'] = $order_ids;
        ShopOrderCache::del($order_ids);
        return $param;
    }

    /**
     * 订单追评截图提交
     * @Author: 易军辉
     * @DateTime:2024-09-20 15:48
     * @param $id 订单ID
     * @param $param
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function submitCommentScreenshot($id, $param = [])
    {
        $model = new ShopOrderCommentModel();
        $info = $model
            ->where('shop_order_id',$id)
            ->where('member_id',member_id(true))
            ->where('status',1)
            ->where('comment_status',3)
            ->where('id',$param['order_comment_id'])
            ->find();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);

        if (empty($info)) {
            exception("未查询到需要提交追评截图的任务");
            return false;
        }

        $res = $model->where($pk, $info['id'])->update([
            'status'=>2,
            'evaluate_image_id'=>$param['evaluate_image_id'],
            'submit_time'=>datetime(),
        ]);
        if (empty($res)) {
            exception();
        }
        return $param;
    }

    /**
     * 操作订单超时回池
     * @Author: 易军辉
     * @DateTime:2024-11-08 14:23
     * @return int
     */
    public static function goodsRevokeOrder()
    {
        $status_str = ShopOrderModel::getStatus('o_listing', 1).",".
                        ShopOrderModel::getStatus('o_select', 1).",".
                        ShopOrderModel::getStatus('o_taking', 1);
        $product_str = ShopProductModel::getStatus('in',1).",".
                        ShopProductModel::getStatus('revoke',1);
        $sql = <<<SQL
                SELECT a.id
                from ya_shop_order as a
                LEFT JOIN ya_shop_product as product on a.shop_product_id = product.id
                where
                a.is_delete =0
                and product.is_delete =0
                and product.is_disable =0
                and a.`status` in({$status_str})
                and product.`status` in({$product_str})
                and TIMESTAMPDIFF(HOUR, product.auth_time, NOW()) >= product.e_revoke_time
            SQL;
        $list = Db::query($sql);
        $count = count($list);
        if($count>0){
            $order_ids = array_column($list,'id');
            $res = self::revoke($order_ids,[
                'refund_type'=>[1,2],
                'revoke_remark'=>"任务超时，系统自动撤销",
                'ids'=>$order_ids
            ]);
        }
        return $count;
    }
    /**
     * 订单撤销
     * @Author: 易军辉
     * @DateTime:2024-09-23 16:48
     */
    public static function revoke($ids,$param)
    {
        Db::startTrans();
        try {
            $order_list = Db::name('shop_order')
                ->whereIn('id',$ids)
                ->whereNotIn('status',[ShopOrderModel::getStatus('o_revoke',1)])
                ->where('is_delete',0)
                ->select()
                ->toArray();
            if(count($order_list)<=0){
                exception('未查询到满足撤销条件的订单');
            }
            $shop_product_ids = [];
            foreach ($order_list as $key=>$val){
                $mer_principal = 0 ;//商家支付的本金
                $mer_commission = 0;//商家支付的佣金
                $user_principal = 0;//本金
                $user_commission = 0;//买手所得佣金
                $is_promotion = false;//是否退推广费
                $log_title="";
                $log_remark="";
                $is_principal=$val['is_principal'];//买家本金返款情况：0、未返 1、已返 2、已扣
                $is_commission=$val['is_commission'];//买家佣金返款情况：0、未返 1、已返 2、已扣
                $is_mer_principal=$val['is_mer_principal'];//商家本金支付情况：1、已支付 2、已退
                $is_mer_commission=$val['is_mer_commission'];//商家佣金支付情况：1、已支付 2、已退
                $message_content="您的订单：".$val['id']."已撤销";//通知买家消息内容
                foreach ($param['refund_type'] as $k=>$v){
                    switch ($v){
                        case 1://退商家本金
                            if($val['is_mer_principal']==1){
                                if(bcadd($val['actual_amount'], $val['difference_amount'],2) == $val['principal']){//实付金额+差额=本金
                                    $mer_principal = $val['actual_amount'];//实付金额
                                }else{
                                    $mer_principal = $val['principal'];//本金
                                }
                                if($mer_principal>0){
                                    $log_title .="退商家本金";
                                    $log_remark .="退商家本金：".$mer_principal;
                                    $is_mer_principal = 2;
                                }
                            }
                            break;
                        case 2://退商家佣金
                            if($val['is_mer_commission']==1){
                                $mer_commission = $val['mer_commission'];
                                if($mer_commission>0){
                                    $log_title .=($log_title!=""?",":"")."退商家佣金";
                                    $log_remark .=($log_title!=""?",":"")."退商家佣金：".$mer_commission;
                                    $is_mer_commission = 2;
                                }
                            }
                            //查看是否有发布评论佣金
                            self::revokeCommentCommission(1,$val['id']);
                            break;
                        case 3://扣买家本金
                            if($val['is_principal'] ==1){
                                if(bcadd($val['actual_amount'], $val['difference_amount'],2) == $val['principal']){//实付金额+差额=本金
                                    $user_principal = $val['actual_amount'];//实付金额
                                }else{
                                    $user_principal = $val['principal'];//本金
                                }
                                if($user_principal>0 && $val['member_id'] && $val['member_account_id']){
                                    $log_title .=($log_title!=""?",":"")."扣买家本金";
                                    $log_remark .=($log_title!=""?",":"")."扣买家本金：".$user_principal;
                                    $is_principal = 2;
                                    $consumption_res = MemberService::consumption(
                                        $val['member_id'],
                                        $user_principal,
                                        $user_principal,
                                        0,
                                        null,//撤销订单扣本金
                                        $val['id'],
                                        $val['member_account_id'],
                                        "撤销订单：".$val['id'],
                                        'YHBT'
                                    );
                                    $message_content .=",扣除".MemberBillModel::getType('YHBT',2).$user_principal."元";
                                }
                            }
                            break;
                        case 4://扣买家佣金
                            if($val['is_commission'] ==1) {
                                $user_commission = $val['commission'];
                                $is_promotion = true;
                                if($user_commission>0 && $val['member_id'] && $val['member_account_id']){
                                    $log_title .=($log_title!=""?",":"")."扣买家佣金";
                                    $log_remark .=($log_title!=""?",":"")."扣买家佣金：".$user_commission;
                                    $is_commission = 2;
                                    $consumption_res = MemberService::consumption(
                                        $val['member_id'],
                                        $user_commission,
                                        0,
                                        $user_commission,
                                        null,//撤销订单扣佣金
                                        $val['id'],
                                        $val['member_account_id'],
                                        "撤销订单：".$val['id'],
                                        'PTBT'
                                    );
                                    $message_content .=",扣除".MemberBillModel::getType('PTBT',2).$user_principal."元";
                                }
                            }
                            //查看是否有发布评论佣金
                            self::revokeCommentCommission(2,$val['id']);
                            break;
                    }
                }
                //商家退款
                $mer_money = bcadd($mer_principal, $mer_commission,2);
                if($mer_money>0){
                    $mer_refund = MerchantService::refund(
                        $val['merchant_id'],
                        $mer_money,
                        $mer_principal,
                        $mer_commission,
                        '撤销订单退款',
                        $val['id'],
                        $val['merchant_shop_id'],
                        "订单ID：".$val['id']
                    );
                }

                //买家扣款
//                $user_money = bcadd($user_principal, $user_commission,2);
//                if($user_money>0 && $val['member_id'] && $val['member_account_id']){
//                    $consumption_res = MemberService::consumption(
//                        $val['member_id'],
//                        $user_money,
//                        $user_principal,
//                        $user_commission,
//                        '撤销订单扣款',
//                        $val['id'],
//                        $val['member_account_id'],
//                        "订单ID：".$val['id']
//                    );
//                }
                //退推广费
                if($is_promotion){
                    $order_promotion = Db::name('shop_order_promotion')->where('shop_order_id',$val['id'])->where('is_delete',0)->order(['id'=>'desc'])->find();
                    if($order_promotion){
                        //买家推广
                        if($order_promotion['one_member_id'] && $order_promotion['one_amount']>0){
                            $res = self::refundOrderPromotion(1,$order_promotion['one_member_id'],$order_promotion['one_amount'],$val['id'],$val['merchant_id']);
                            $log_remark .=($log_title!=""?",":"")."扣一级推广买家".$order_promotion['one_member_id']."佣金：".$order_promotion['one_amount'];
                        }
                        if($order_promotion['two_member_id'] && $order_promotion['two_amount']>0){
                            $res = self::refundOrderPromotion(1,$order_promotion['two_member_id'],$order_promotion['two_amount'],$val['id'],$val['merchant_id']);
                            $log_remark .=($log_title!=""?",":"")."扣二级推广买家".$order_promotion['two_member_id']."佣金：".$order_promotion['two_amount'];
                        }
                        if($order_promotion['three_member_id'] && $order_promotion['three_amount']>0){
                            $res = self::refundOrderPromotion(1,$order_promotion['three_member_id'],$order_promotion['three_amount'],$val['id'],$val['merchant_id']);
                            $log_remark .=($log_title!=""?",":"")."扣三级推广买家".$order_promotion['three_member_id']."佣金：".$order_promotion['three_amount'];
                        }
                        //推广员推广
                        if($order_promotion['one_promotion_user_id'] && $order_promotion['one_promotion_amount']>0){
                            $res = self::refundOrderPromotion(2,$order_promotion['one_promotion_user_id'],$order_promotion['one_promotion_amount'],$val['id'],$val['merchant_id']);
                            $log_remark .=($log_title!=""?",":"")."扣一级推广员".$order_promotion['one_promotion_user_id']."佣金：".$order_promotion['one_promotion_amount'];
                        }
                        if($order_promotion['two_promotion_user_id'] && $order_promotion['two_promotion_amount']>0){
                            $res = self::refundOrderPromotion(2,$order_promotion['two_promotion_user_id'],$order_promotion['two_promotion_amount'],$val['id'],$val['merchant_id']);
                            $log_remark .=($log_title!=""?",":"")."扣二级推广员".$order_promotion['two_promotion_user_id']."佣金：".$order_promotion['two_promotion_amount'];
                        }
                        if($order_promotion['three_promotion_user_id'] && $order_promotion['three_promotion_amount']>0){
                            $res = self::refundOrderPromotion(2,$order_promotion['three_promotion_user_id'],$order_promotion['three_promotion_amount'],$val['id'],$val['merchant_id']);
                            $log_remark .=($log_title!=""?",":"")."扣三级推广员".$order_promotion['three_promotion_user_id']."佣金：".$order_promotion['three_promotion_amount'];
                        }
                    }
                }
                $create_uid = operate_user_id();
                //订单日志
                $log_res = ShopOrderLogService::addByCode('YCX',[
                    'merchant_id'=>$val['merchant_id'],
                    'shop_order_id'=>$val['id'],
                    'order_status'=>ShopOrderModel::getStatus('o_revoke',1),
                    'create_uid'=>$create_uid,
                    'remark'=>$log_remark,
                    'title'=>$log_title!=""?"已撤销(".$log_title.")":"已撤销",
                ]);
                //更改订单状态
                $order_edit = Db::name('shop_order')
                    ->where('id',$val['id'])
                    ->update([
                        'revoke_type'=>2,
                        'revoke_uid'=>$create_uid,
                        'revoke_time'=>datetime(),
                        'old_status'=>$val['status'],
                        'revoke_remark'=>$param['revoke_remark'],
                        'status'=>ShopOrderModel::getStatus('o_revoke',1),
                        'is_principal'=>$is_principal,
                        'is_commission'=>$is_commission,
                        'is_mer_principal'=>$is_mer_principal,
                        'is_mer_commission'=>$is_mer_commission,
                    ]);
                if($order_edit){
                    array_push($shop_product_ids,$val['shop_product_id']);
                }
                //给买家发送消息通知
                MemberMessageService::add([
                    'title'=>'撤销通知',
                    'content'=>$message_content,
                    'member_id'=>$val['member_id'],
                    'data_id'=>$val['id'],
                ]);
            }
            // 提交事务
            Db::commit();
            /********************处理商品状态*********************************/
            if(count($shop_product_ids)>0){
                ShopProductService::changeStatus(array_unique($shop_product_ids));
            }
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        if (isset($errmsg)) {
            exception($errmsg);
        }
        return true;
    }

    /**
     * 撤销订单发布评论佣金
     * @Author: 易军辉
     * @DateTime:2024-09-25 14:49
     * @param $type 1、退商家佣金 2、扣买家佣金
     * @param $shop_order_id 订单ID
     * @return true
     */
    private static function revokeCommentCommission($type=1,$shop_order_id=0)
    {
        //查询是否有评论
        $order_comment = Db::name('shop_order_comment')
            ->where('is_delete',0)
            ->where('shop_order_id',$shop_order_id)
            ->where('comment_status',2)
            ->when($type,function($query)use($type){
                if($type==1){
                    $query->where('is_mer_pay',1);
                }else if($type==2){
                    $query->where('is_member_pay',1);
                }
            })
            ->order(['create_time'=>'asc'])
            ->find();
        if($order_comment && $type==1){
            //退款
            $consumption_res = MerchantService::refund(
                $order_comment['merchant_id'],
                $order_comment['mer_commission'],
                0,
                $order_comment['mer_commission'],
                '评论撤销退款',
                $order_comment['shop_order_id'],
                null,
                "订单ID：".$order_comment['shop_order_id']
            );
            return Db::name('shop_order_comment')->where('id',$order_comment['id'])->update([
                'is_mer_pay'=>2,
                'update_uid'=>operate_user_id(),
                'update_time'=>datetime(),
            ]);
        }else if($order_comment && $type==2){
            //扣款
            $consumption_res = MemberService::consumption(
                $order_comment['member_id'],
                $order_comment['commission'],
                0,
                $order_comment['commission'],
                null,//评论撤销扣款
                $order_comment['shop_order_id'],
                $order_comment['member_account_id'],
                "撤销评论订单：".$order_comment['shop_order_id'],
                'PTBT'
            );
            //给买家发送消息通知
            MemberMessageService::add([
                'title'=>'撤销通知',
                'content'=>"您的订单：".$order_comment['shop_order_id']."已撤销，需扣除评论补贴".$order_comment['commission']."元",
                'member_id'=>$order_comment['member_id'],
                'data_id'=>$order_comment['shop_order_id'],
            ]);
            return Db::name('shop_order_comment')->where('id',$order_comment['id'])->update([
                'is_member_pay'=>2,
                'update_uid'=>operate_user_id(),
                'update_time'=>datetime(),
            ]);
        }
        return true;
    }

    /**
     * 扣除订单推广费
     * @Author: 易军辉
     * @DateTime:2024-09-23 20:45
     * @param $type 1、买家推广员 2、商家推广员
     * @param $member_id 推广员ID
     * @param $amount 推广费
     * @param $order_id 订单ID
     * @param $merchant_id 商家ID
     */
    private static function refundOrderPromotion($type=1,$member_id=0,$amount=0,$order_id=0,$merchant_id=0)
    {
        if($member_id && $amount>0){
            if($type == 1){
                //给买家发送消息通知
                MemberMessageService::add([
                    'title'=>'撤销通知',
                    'content'=>"你的下级订单：".$order_id."，需扣除".$amount."元，已撤销完成退款",
                    'member_id'=>$member_id,
                    'data_id'=>$order_id,
                ]);
                return MemberService::consumption(
                    $member_id,
                    $amount,
                    0,
                    $amount,
                    null,//撤销订单扣除推广佣金
                    $order_id,
                    null,
                    "撤销订单：".$order_id,
                    'XJTC'
                );
            }else if($type == 2){
                return PromotionUserService::consumption(
                    $member_id,
                    $amount,
                    '撤销订单扣除推广佣金',
                    $order_id,
                    "商家ID：".$merchant_id."，订单ID：".$order_id,
                    $merchant_id,
                    $order_id
                );
            }
        }
        return false;
    }

    /**
     * 修改订单状态
     * @Author: 易军辉
     * @DateTime:2024-09-24 15:17
     * @param $id 订单id
     * @param $param 参数
     * @return mixed
     * @throws \think\Exception
     */
    public static function edit_status($id,$param)
    {
        $model = new ShopOrderModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $info = $model->find($id);
        if (empty($info)) {
            exception('订单信息不存在：' . $id);
            return [];
        }
        $data['update_uid']  = user_id();
        $data['update_time'] = datetime();
        $data['old_status'] = $info['status'];
        $data['status'] = $param['status'];

        if(
            $data['status'] == ShopOrderModel::getStatus('o_listing')
            || $data['status'] == ShopOrderModel::getStatus('o_select')
            || $data['status'] == ShopOrderModel::getStatus('o_taking')
        ){
            $data['member_id']=null;
            $data['member_account_id']=null;
            $data['pending_member_id']=null;
            $data['pending_member_account_id']=null;
            $data['order_on']=null;
            $data['actual_amount']=0;
        }

        $res = $model->where($pk, $info[$pk])->update($data);
        if (empty($res)) {
            exception();
        }
        //订单日志
        $log_res = ShopOrderLogService::addByCode('DDZTBG',[
            'merchant_id'=>$info['merchant_id'],
            'shop_order_id'=>$info['id'],
            'order_status'=>$data['status'],
            'create_uid'=>user_id(),
            'remark'=>"【".ShopOrderModel::getStatus($info['status'],2)."】变更为【".ShopOrderModel::getStatus($data['status'],2)."】",
        ]);
        /********************处理商品状态*********************************/
        if(
            $param['status'] == ShopOrderModel::getStatus('o_success',1)
            || $param['status'] == ShopOrderModel::getStatus('o_revoke',1)
        ){
            ShopProductService::changeStatus($info['shop_product_id']);
        }
        ShopOrderCache::del($id);
        return $param;
    }
    /**
     * 订单奖惩
     * @Author: 易军辉
     * @DateTime:2024-09-24 15:17
     * @param $id 订单id
     * @param $param 参数
     * @return mixed
     * @throws \think\Exception
     */
    public static function edit_rewards($id,$param)
    {
        $model = new ShopOrderModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $info = $model->find($id);
        if (empty($info)) {
            exception('订单信息不存在：' . $id);
            return [];
        }
        // 启动事务
        $model->startTrans();
        try {
            $remark = "";
            switch ($param['object']){
                case 1://商家
                    $remark = "奖惩商家";
                    $refund_principal=0;//退款本金
                    $refund_commission=0;//退款佣金
                    $consumption_principal=0;//扣本金
                    $consumption_commission=0;//扣佣金
                    if($param['principal']>0){
                        $refund_principal = $param['principal'];
                    }else if($param['principal']<0){
                        $consumption_principal= abs($param['principal']);
                    }
                    if($param['commission']>0){
                        $refund_commission=$param['commission'];
                    }else if($param['commission']<0){
                        $consumption_commission=abs($param['commission']);
                    }
                    //退款
                    if($refund_principal!=0 || $refund_commission!=0){
                        $mer_refund = MerchantService::refund(
                            $info['merchant_id'],
                            bcadd($refund_principal, $refund_commission,2),
                            $refund_principal,
                            $refund_commission,
                            '平台奖惩',
                            $info['id'],
                            $info['merchant_shop_id'],
                            $param['remark'].($param['remark']?",":"")."订单ID：".$info['id']
                        );
                    }
                    //扣款
                    if($consumption_principal!=0 || $consumption_commission!=0){
                        $consumption_res = MerchantService::consumption(
                            bcadd($consumption_principal, $consumption_commission,2),
                            $consumption_principal,
                            $consumption_commission,
                            '平台奖惩',
                            $info['id'],
                            $info['merchant_shop_id'],
                            $param['remark'].($param['remark']?",":"")."订单ID：".$info['id'],
                            $info['merchant_id'],
                            true
                        );
                    }
                    break;
                case 2://买家
                    $remark = "奖惩买家";
                    if(!$info['member_id'] || !$info['member_account_id']){
                        exception("该订单无买家接单，无法完成奖惩操作");
                    }
                    $refund_principal=0;//退款本金
                    $refund_commission=0;//退款佣金
                    $consumption_principal=0;//扣本金
                    $consumption_commission=0;//扣佣金
                    if($param['principal']>0){
                        $refund_principal = $param['principal'];
                    }else if($param['principal']<0){
                        $consumption_principal= abs($param['principal']);
                    }
                    if($param['commission']>0){
                        $refund_commission=$param['commission'];
                    }else if($param['commission']<0){
                        $consumption_commission=abs($param['commission']);
                    }
                    //退款
                    if($refund_principal!=0 || $refund_commission!=0){
                        $commission_res = MemberService::income(
                            $info['member_id'],
                            bcadd($refund_principal, $refund_commission,2),
                            $refund_principal,
                            $refund_commission,
                            null,//平台奖惩
                            $info['id'],
                            $info['member_account_id'],
                            $param['remark'].($param['remark']?"，":"")."结算订单：".$info['id'],
                            'PTJC'
                        );
                    }
                    //扣款
                    if($consumption_principal!=0 || $consumption_commission!=0){
                        $consumption_res = MemberService::consumption(
                            $info['member_id'],
                            bcadd($consumption_principal, $consumption_commission,2),
                            $consumption_principal,
                            $consumption_commission,
                            null,//平台奖惩
                            $info['id'],
                            $info['member_account_id'],
                            $param['remark'].($param['remark']?"，":"")."结算订单：".$info['id'],
                            'PTJC'
                        );
                    }
                    break;
            }
            //订单日志
            $remark .="(本金：".$param['principal']."，佣金：".$param['commission'].")";
            $log_res = ShopOrderLogService::addByCode('DDJC',[
                'merchant_id'=>$info['merchant_id'],
                'shop_order_id'=>$info['id'],
                'order_status'=>$info['status'],
                'create_uid'=>user_id(),
                'remark'=>$remark,
            ]);
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }
        if (isset($errmsg)) {
            exception($errmsg);
        }
        return $param;
    }

    /**
     * 平台补贴商品抢购订单
     * @Author: 易军辉
     * @DateTime:2024-10-22 15:41
     * @param $shop_product_id 商品ID
     * @param $param
     */
    public static function allocationOrder($shop_product_id, $param = [])
    {
        //效验
        $validation_res = MemberAccountService::getMemberOrderValidation($param['member_id'],$shop_product_id,1,true);
        if(!$validation_res){
            exception('系统繁忙，请稍后再试');
        }
        $model = new ShopOrderModel();
        $order_status = [
            ShopOrderModel::getStatus('o_select', 1),
            ShopOrderModel::getStatus('o_taking', 1),
        ];
        $info = $model
            ->alias('a')
            ->leftJoin('shop_product','a.shop_product_id=shop_product.id')
            ->where('shop_product.id', $shop_product_id)
            ->where('shop_product.is_disable', 0)
            ->where('shop_product.is_delete', 0)
            ->where('shop_product.status', 'in',[
                ShopProductModel::getStatus('in', 1)
            ])
            ->where('a.status', 'in',$order_status)
            ->where('a.is_delete', 0)
            ->field('a.*')
            ->order(['a.advertising_time'=>'asc','a.id'=>'asc'])
            ->find();
        if (empty($info)) {
            exception('对不起，该商品已被抢购一空');
        }
        $order_id = 0;
        // 启动事务
        $model->startTrans();
        try {
            $where =[
                ['id','=',$info['id']],
                ['is_delete','=',0],
                ['status','in',$order_status]
            ];
            $edit_data = [
                'meet_time'=>date('Y-m-d H:i:s'),
                'status'=>ShopOrderModel::getStatus('o_operation',1),
                'old_status'=>$info['status'],
                'member_id'=>$param['member_id'],
            ];
            $data = self::customEdit($where, $edit_data);
            if($data){
                $log_res = ShopOrderLogService::addByCode('MJJD',[
                    'merchant_id'=>$info['merchant_id'],
                    'shop_order_id'=>$info['id'],
                    'order_status'=>$edit_data['status'],
                    'create_uid'=>$param['member_id'],
                    'remark'=>'接单用户ID：'.$param['member_id']
                ]);
                $order_id = $info['id'];
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }
        if (isset($errmsg)) {
            exception($errmsg);
        }
        return compact('order_id');
    }

    /**
     * 查询抢单列表
     * @Author: 易军辉
     * @DateTime:2024-10-28 17:54
     * @param $param 条件参数
     * @param $page 页数
     * @param $limit 数量
     * @param $order 排序
     * @param $field 字段
     */
    public static function getGrabList($param = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        /*************************************公共参数***********************************/
        $where[] = ['is_delete','=',0];
        $where[] = ['shop_product_type_code','<>',ShopProductTypeModel::PTBT];
        $where[] = ['status','in',[
            ShopOrderModel::getStatus('o_select', 1),
            ShopOrderModel::getStatus('o_taking', 1),
        ]];
        $msg = "";
        /*************************************店铺平台***********************************/
        $store_platform_id = 0;
        if(isset($param['member_account_id']) && $param['member_account_id']>0){
            $store_platform_id = Db::name('member_account')->where('id',$param['member_account_id'])->value('store_platform_id');
            //效验
            $validation_res = MemberAccountService::getMemberAccountOrderValidation($param['member_id'],$param['member_account_id'],1,null);
            switch ($validation_res['code']){
                case 0:
                    $msg = $validation_res['msg'];
                    break;
                case 1:
                    if(count($validation_res['data'])>0){
                        $where[] = ['id','in',$validation_res['data']];
                    }else{
                        $where[] = ['id','=',0];
                    }
                    break;
            }
        }else if(isset($param['store_platform_id']) && $param['store_platform_id']>0){
            $store_platform_id = $param['store_platform_id'];
        }
        if($store_platform_id>0){
            $store_platform_ids = SettingStorePlatformModel::handleTaobaoIds($store_platform_id);
            if(!is_array($store_platform_ids)){
                $store_platform_ids = [$store_platform_ids];
            }
            $where[] = ['store_platform_id','in',$store_platform_ids];
        }
        /*************************************查询字段***********************************/
        $sql = self::getListSql($where,$order,$field);
        if ($page == 0 || $limit == 0) {
            return json_decode(json_encode(Db::query($sql)), true);
        }
        $count =  Db::query("select count(*) as count from (".$sql.") as co");
        $count=$count[0]['count'];
        $pages = ceil($count / $limit);
        // 计算偏移量
        $offset = ($page - 1) * $limit;
        $list = Db::query($sql. " LIMIT $offset, $limit");
        //增值服务过滤买号条件编码
        $range_codes = SettingPriceRangeModel::RANGE_CODES;
        $range_codes[] = 'Self_selection';//商家自选买号过滤掉
        foreach ($list as $key=>$item) {
            //店铺平台图片
            if(isset($item['platform_image_id'])){
                $file = FileService::info($item['platform_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['platform_image_url'] =$file['file_url'];
                }
            }
            //商品缩略图
            if(isset($item['goods_image_id'])){
                $file = MerchantFileService::info($item['goods_image_id']);
                if($file && isset($file['file_url'])){
                    $list[$key]['goods_image_url'] =$file['file_url'];
                }
                // 查找最后一个点的位置
                $lastDotPosition = strrpos($file['file_path'], '.');
                $newFilePath = substr($file['file_path'], 0, $lastDotPosition) . '_pixelated' . substr($file['file_path'], $lastDotPosition);
                $new_file_path = self::pixelateImage($file['file_path'],$newFilePath,30);
                if($new_file_path){
                    $list[$key]['goods_image_url'] = file_url($new_file_path);
                }
            }

            //状态名称
            $list[$key]['status_title'] = ShopOrderModel::getStatus($item['status'],2);

            //评论类型
            if(isset($item['comment_type'])){
                $list[$key]['comment_type_str'] = SettingPriceRangeModel::getCommentType($item['comment_type'],1);
            }
            //进店方式
            if(isset($item['enter_type'])){
                $list[$key]['enter_type_str'] = SettingPriceRangeModel::getEnterType($item['enter_type'],1);
            }
            //店铺名称处理
            if (isset($item['shop_title'])  && array_key_exists('status', $item)){
                $list[$key]['shop_title'] = self::hideSpace($item['shop_title'],2);
            }
            //增值服务附加要求处理
            $list[$key]['user_describes'] =[];
            if(
                array_key_exists('shop_product_id',$item)
                && array_key_exists('setting_price_range_ids',$item)
                && $item['setting_price_range_ids']
            ) {
                $list[$key]['user_describes'] = Db::name('shop_product_increment')->alias('a')
                    ->leftJoin('setting_price_range','a.setting_price_range_id=setting_price_range.id')
                    ->where('a.shop_product_id',$item['shop_product_id'])
                    ->whereIn('a.setting_price_range_id',$item['setting_price_range_ids'])
                    ->whereNotIn('a.setting_price_range_code',$range_codes)
                    ->column('setting_price_range.user_describe');
            }
        }
        return compact('count', 'pages', 'page', 'limit', 'list','msg');
    }

    /**
     * 抢单
     * @Author: 易军辉
     * @DateTime:2024-10-29 18:57
     * @param $shop_order_id 订单id
     * @param $param 参数
     */
    public static function grabOrder($shop_order_id, $param = [])
    {
        //效验
        $validation_res = MemberAccountService::getMemberAccountOrderValidation($param['member_id'],$param['member_account_id'],2,$shop_order_id);
        switch ($validation_res['code']){
            case 0:
                exception($validation_res['msg']);
                break;
            case 1:
                $order_ids = count($validation_res['data'])>0?array_column($validation_res['data'],'id'):[];
                if(count($validation_res['data'])>0 && in_array($shop_order_id, $order_ids)){
                    $info = $validation_res['data'][0];
                    $order_status = [
                        ShopOrderModel::getStatus('o_select', 1),
                        ShopOrderModel::getStatus('o_taking', 1),
                    ];
                    $where =[
                        ['id','=',$info['id']],
                        ['is_delete','=',0],
                        ['status','in',$order_status]
                    ];
                    $edit_data = [
                        'meet_time'=>date('Y-m-d H:i:s'),
                        'status'=>ShopOrderModel::getStatus('o_operation',1),
                        'old_status'=>$info['status'],
                        'member_id'=>$param['member_id'],
                        'member_account_id'=>$param['member_account_id'],
                    ];
                    $data = self::customEdit($where, $edit_data);
                    if($data){
                        $log_res = ShopOrderLogService::addByCode('MJJD',[
                            'merchant_id'=>$info['merchant_id'],
                            'shop_order_id'=>$info['id'],
                            'order_status'=>$edit_data['status'],
                            'create_uid'=>$param['member_id'],
                            'remark'=>'接单买号ID：'.$param['member_account_id']
                        ]);
                        return $info['id'];
                    }
                }else{
                    exception("该订单已被抢，请下拉刷新重新抢");
                }
                break;
        }
        return false;
    }
}
